题目描述:
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.
思路解析:
- 对于查找回文的子串,分为两种:aba,bb;
- 所以从左至右遍历,每个字符作为中间位置,还有两字符空格作为中间位置,做对称比较
- 需要一个装最大子串的longest字符串来存储。
代码:
public class Solution {
public String longestPalindrome(String s) {
if(s==null||s.length()==0)
return "";
String longest = s.substring(0,1);
for(int i=0;i<s.length();i++){
String tmp = helper(s,i,i);
if(tmp.length()>longest.length()){
longest = tmp;
}
tmp = helper(s,i,i+1);
if(tmp.length()>longest.length()){
longest = tmp;
}
}
return longest;
}
private String helper(String s, int begin, int end){
while(begin>=0&& end<=s.length()-1 && s.charAt(begin) ==s.charAt(end)){
begin--;
end++;
}
return s.substring(begin+1,end);
}
}