[LeetCode] 5. Longest Palindromic Substring _Medium tag: Two pointers
2021/7/29 6:07:53
本文主要是介绍[LeetCode] 5. Longest Palindromic Substring _Medium tag: Two pointers,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
Given a string s
, return the longest palindromic substring in s
.
Example 1:
Input: s = "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: s = "cbbd" Output: "bb"
Example 3:
Input: s = "a" Output: "a"
Example 4:
Input: s = "ac" Output: "a"
Constraints:
1 <= s.length <= 1000
s
consist of only digits and English letters (lower-case and/or upper-case),
Ideas:
1. 利用 来建一个palin, T: O(n * n) , S: O(n * n), 然后再用两个for loop 去看是否为palin,再更新ans及ans_length, 但是Leetcode上Time Limit Exceeded.
Code
class Solution: def longestPalindrome(self, s: str) -> str: palin = self.generatePalin(s) n = len(s) ans_length, ans = 1, s[0] for i in range(n): for j in range(i, n): if palin[i][j] and j - i + 1 > ans_length: ans_length, ans = j - i + 1, s[i : j + 1] return ans def generatePalin(self, s): n = len(s) palin = [[False] * n for _ in range(n)] for i in range(n): palin[i][i] = True if i > 0: palin[i - 1][i] = s[i] == s[i - 1] for width in range(2, n): for start in range(n): if start + width < n and s[start] == s[start + width]: palin[start][start + width] = palin[start + 1][start + width - 1] return palin
Idea 2: 用一个helper function, 每次往两边衍生, 如果当前是palin的话,然后再更新ans
Code
class Solution: def longestPalindrome(self, s: str) -> str: #palin = self.generatePalin(s) n = len(s) ans =s[0] for i in range(n): # odd case, ex: "aba" odd = self.helper(s, i, i) if len(odd) > len(ans): ans = odd # even case even = self.helper(s, i, i + 1) if len(even) > len(ans): ans = even return ans def helper(self, s, l, r): while l >=0 and r <len(s) and s[l] == s[r]: l-=1 r+=1 return s[l+1:r]
这篇关于[LeetCode] 5. Longest Palindromic Substring _Medium tag: Two pointers的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-15你可能误会了!用 TypeScript 的正确姿势并不是这样子的
- 2025-01-14成本考量下,开源 CMS 内容管理系统为何脱颖而出
- 2025-01-14用Diffusers结合CivitAI模型、LoRAs和文本反转生成更高质量的图像
- 2025-01-14利用ChatGPT自动构建知识图谱的方法讲解
- 2025-01-14?? 缓存增强生成(CAG):一个崛起的RAG竞争对手?
- 2025-01-14Apache Spark及分布式计算概览
- 2025-01-14AWS入门第一篇——云基础与EC2实例详解
- 2025-01-14Apache Iceberg:现代数据栈中的“新一代Hadoop”?
- 2025-01-14深入理解 ECMAScript 2024 新特性:Promise.withResolvers
- 2025-01-13SRM vs SCM:企业管理中的差异战略与实践