leetcode5. Longest Palindromic Substring
题意:
给定一个字符串s,找到s中最长的回文子字符串。可以假设s的最大长度为1000。
思路:
O(n)遍历s,然后以每个char为回文的中心,向两边尽可能延长,以此找出最长的回文。
初始化left和right的时候,因为回文的特征直接跳过与该char相同的字符。
ac代码:
C++
class Solution {
public:
string longestPalindrome(string s) {
int len = s.length();
int res = 0;
int start = -1;
for(int i = 0; i < len; i++)
{
int u = i;
while(i<len-1 && s[i+1] == s[i]) i++;
int l = u - 1;
int r = i + 1;
while(l>=0&&r<len&&s[l] == s[r]) {l--; r++;}
//res = max(r - l - 1, res);
if(r - l -1 > res)
{
res = r - l -1;
start = l ;
}
}
return s.substr(start + 1,res);
}
};
python
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
start = -1
ans = 0
i = 0
while i < len(s):
l = i - 1
while i < len(s) - 1 and s[i+1] == s[i]:
i += 1
r = i + 1
while l >= 0 and r < len(s) and s[l] == s[r]:
l -= 1
r += 1
if r - l - 1 >= ans:
ans = r - l - 1
start = l
i += 1
return s[start + 1:start + 1 + ans]