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.
解法:
中心展开法(推荐)
动态规划
code
public class LongestPalindromicSubstring {
public String longestPalindrome(String s) {
if (s == null || s.length() == 0)
return "";
String result = null;
int max = 0;
for (int i = 0; i < s.length(); i++) {
String s1 = getLongestLength(s, i, i);
String s2 = getLongestLength(s, i, i + 1);
if (s1.length() > max) {
max = s1.length();
result = s1;
}
// "bb"
if (s2.length() > max) {
max = s2.length();
result = s2;
}
}
return result;
}
public String getLongestLength(String s, int left, int right) {
int len = s.length();
while (left >= 0 && right < len) {
if (s.charAt(left) != s.charAt(right)) {
continue;
}
left--;
right++;
}
return s.substring(left + 1, right); // index -1
}
}