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.
给定一个字符串,求出其最长回文子串。
public class Solution {
public String longestPalindrome(String s) {
if (s.length() == 0) {
return null;
}
if (s.length() == 1) {
return s;
}
String longest = s.substring(0, 1);
for (int i = 0; i < s.length(); i++) {
String t1 = helper(i, i, s);
if (longest.length() < t1.length()) {
longest = t1;
}
String t2 = helper(i, i+1, s);
if (longest.length() < t2.length()) {
longest = t2;
}
}
return longest;
}
private String helper(int beg, int end, String s) {
while (beg>-1 && end<s.length() && s.charAt(beg)==s.charAt(end)) {
beg--;
end++;
}
return s.substring(beg+1, end);
}
}