Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example:
Input: "cbbd" Output: "bb"
自己实现的代码
public static String longestPalindrome(String s) {
String sb = s.substring(0, 1);
int end = s.length();
int j = 0;
int i = 0;
int begin = 1;
while (end - begin > (sb.length() >> 1)) {
i = j = begin;
i--; j++;
sb = assignMaxString(s, sb, end, j, i);
i = j = begin++;
i--;
sb = assignMaxString(s, sb, end, j, i);
}
return sb;
}
private static String assignMaxString(String s, String sb, int end, int j, int i) {
String s0 = null;
if (j < end && s.charAt(i--) == s.charAt(j++)) {
while (i > -1 && j < end && s.charAt(i) == s.charAt(j)) {i--; j++;};
s0 = s.substring(i+1, j);
if(sb.length() < s0.length()) {
sb = s0;
}
}
return sb;
}
官方的代码:
public String longestPalindrome(String s) {
int start = 0, end = 0;
for (int i = 0; i < s.length(); i++) {
int len1 = expandAroundCenter(s, i, i);
int len2 = expandAroundCenter(s, i, i + 1);
int len = Math.max(len1, len2);
if (len > end - start) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return s.substring(start, end + 1);
}
private int expandAroundCenter(String s, int left, int right) {
int L = left, R = right;
while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
L--;
R++;
}
return R - L - 1;
}