您的位置:首页 > 其它

LeetCode 147 Longest Palindromic Substring

2014-11-01 16:45 309 查看
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.

分析:

对于每一个位置,都向两边找对称的字串,更新最长对称字串。

注意,对称有两种情况,

1,aba的情况

2,abba的情况

public class Solution {
public String longestPalindrome(String s) {
if(s==null || s.isEmpty())
return null;
if(s.length()==1)
return s;
String longest = s.substring(0,1);
for(int i=0; i<s.length(); i++){
//有一个对称中心的情况,例如1,2,1的情况
String tmp = helper(s,i,i);
if(tmp.length() > longest.length())
longest = tmp;
//没有对称中心的情况,例如1,2,2,1的情况
tmp = helper(s,i,i+1);
if(tmp.length()>longest.length())
longest = tmp;
}
return longest;
}

public 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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息