题目
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"
class Solution {
private int start, maxLen;
public String longestPalindrome(String s) {
int n = s.length();
if (n < 2) {
return s;
}
for (int i = 0; i < n - 1; i++) {
extendPalindrome(s, i, i);
extendPalindrome(s, i, i + 1);
}
return s.substring(start, start + maxLen);
}
public void extendPalindrome(String s, int j, int k) {
while (j >= 0 && k < s.length() && s.charAt(j) == s.charAt(k)) {
j--;
k++;
}
if (maxLen < k - j - 1) {
start = j + 1;
maxLen = k - j - 1;
}
}
}