Longest Palindromic Substring
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
Example2:
Input: "cbbd"
Output: "bb"
Solution:
private int start = 0;
private int end = 0;
public String longestPalindrome(String s) {
int length = s.length();
if (length < 2) {
return s;
}
for (int i = 0; i < length; i++) {
// 奇
searchPalindrome(s, i, i);
// 偶
searchPalindrome(s, i, i + 1);
}
return s.substring(start, end);
}
private void searchPalindrome(String s, int x, int y) {
int length = s.length();
while (x > -1 && y < length && s.charAt(x) == s.charAt(y)) {
x--;
y++;
}
if (y - x > end - start + 1) {
start = x + 1;
end = y;
}
}