<div>
Given a string s, return the longest palindromic substring in s.
Example 1:
<pre>Input: s = "babad" Output: "bab" Explanation: "aba" is also a valid answer. </pre>
Example 2:
<pre>Input: s = "cbbd" Output: "bb" </pre>
Constraints:
1 <= s.length <= 1000sconsist of only digits and English letters.
</div>
题目大意:
最长回文
解题思路:
遍历每个字符,以该字符为中心,往前后比较是否回文,求最长回文
解题步骤:
N/A
注意事项:
- 回文字符串的中心位可以为1个或2个
- 此题求最长回文字符串,而不是其长度
- 避免死循环,记得i -= 1, j += 1
- Line 63 若不相等,要break,或者return[i + 1:j]和下面return一样
Python代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19def longestPalindrome(self, s: str) -> str:
res = ''
for i in range(len(s)):
tmp = self.longestPalindromeFromCenter(s, i, i)
if len(tmp) > len(res):
res = tmp
if i + 1 < len(s):
tmp = self.longestPalindromeFromCenter(s, i, i + 1)
if len(tmp) > len(res):
res = tmp
return res
def longestPalindromeFromCenter(self, s, left, right):
while left >= 0 and right <= len(s) - 1:
if s[left] != s[right]:
break
left -= 1
right += 1
return s[left + 1:right]
算法分析:
时间复杂度为<code>O(n<sup>2</sup>)</code>,空间复杂度O(1)


