题目
Given a string
S
, find the longest palindromic substring in
S
. You may assume that the maximum length of
S
is 1000, and there exists one unique longest palindromic substring.
思路
题目是要求出字符串中的最长回文子串。定义计数变量cnt用于存储回文子串的长度,存储回文子串开始位置的变量start,光标cur,光标左右位置left和right。可以分为两种情况:1.连续相同字符如aabb这样的,遇到相同字符则cnt+1,然后光标移动开始下次循环;2.没有连续相同字符但是以某个字符对称如abcba,遇到对称字符则cnt+2,然后光标移动开始下次循环。最后substring(start,start+cnt)即为所求回文子串。
代码
Python
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
#cur是光标,maximum记录回文最大长度,cnt用于临时存储回文子串的长度,start是回文子串起始位置
cur,maximum = 1,1
cnt,start = 0,0
if (len(s) == 2):
if (s[0]==s[1]):
return s
while (cur < len(s)-1) & ((len(s)-cur-1)*2>maximum):
left = cur - 1
right = cur + 1
cnt = 1
if (s[left] == s[cur]) | (s[right] == s[cur]):
while(left >= 0):
if s[left] == s[cur]:
cnt += 1
left -= 1
else:
break
while(right <= len(s)-1):
if s[right] == s[cur]:
cnt += 1
right += 1
else:
break
cur = right
while (left >= 0) & (right <= len(s)-1):
#处理类似asddddddsa这样的情况
if s[left] == s[right]:
cnt += 2
left -= 1
right += 1
else:
break
if cnt > maximum:
maximum = cnt
start = left + 1
else:
#处理类似abcdcba这样以某字符对称的回文情况
while (left >= 0) & (right <= len(s)-1):
#处理类似asddddddsa这样的情况
if s[left] == s[right]:
cnt += 2
left -= 1
right += 1
else:
break
cur += 1
if cnt > maximum:
maximum = cnt
start = left + 1
return s[start:start+maximum]
Java
public class Solution {
public String longestPalindrome(String s) {
char[] str=s.toCharArray();
int max=1;//record max length of palindrome
int cur=1;
int left,right;
int cnt;//record temp max length of palindrome
int start=0;//record longest palindrome beginning location
if(str.length==2&&str[0]==str[1]) return s;
while(cur<str.length-1&&(str.length-cur-1)*2>max){//处理长度大于三的字符串
left=cur-1;
right=cur+1;
cnt=1;
if(str[left]==str[cur]||str[right]==str[cur]){//判断是否有连续相同的字符
while(left>=0){
if(str[left]==str[cur]){
cnt++;
left--;
}
else break;
}
while(right<=str.length-1){
if(str[right]==str[cur]){
cnt++;
right++;
}
else break;
}
cur=right;//reset cur location
while(left>=0&&right<=str.length-1){// 类似'cbaaaaaabc'的情况
if(str[left]==str[right]){
cnt=cnt+2;
left--;
right++;
}
else break;
}
if(cnt>max){
max=cnt;
start=left+1;// 最长回文子串的开始位置
}
}
else{// 以光标为中心对称的回文字符串,如sdfgfdl
while(left>=0&&right<=str.length-1){
if(str[left]==str[right]){
cnt=cnt+2;
left--;
right++;
}
else break;
}
cur++;
if(cnt>max){
max=cnt;
start=left+1;
}
}
}
return s.substring(start,start+max);
}
}