Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
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 String longestPalindrome(String s) {
if (s == null || s.length() <= 1) return s;
final char[] chars = s.toCharArray();
int len = 1;//回数长度
int left = 0;
int right = 0;
for (int i = 0; i < chars.length; ++i) {
for (int j = chars.length - 1; j > i; --j) {
if ((j - i + 1) > len) {
if (isPalindrome(chars, i, j)) {
len = j - i + 1;
left = i;
right = j;
}
} else {
break;
}
}
}
return s.substring(left, right + 1);
}
//判断是否是回数
private boolean isPalindrome(char[] chars, int left, int right) {
int i = left;
int j = right;
while (i < j) {
if (chars[i++] != chars[j--]) {
return false;
}
}
return true;
}
网友评论