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.
思路:遍历字符串,以某一字符为中心,向两边扩展,判断两边对应的字符是否相等。
如:(1)对于字符串"dabcbag",最长回文子字符串为"abcba", 长度为5,为奇数。当遍历到字符c时,以字符串c为中心,记两边的字符下标分别为left,right,向两边扩展,left--, right++。判断两边的字符是否相等,b和b相等,再次向左右两边扩展,a和a相等,直到两边对应位置上的字符不相等,此时记录下长度(right-left+1)。
(2)同时存在"dabccbag",其最大回文字符串长度为6,即为偶数,"abccba"。这个时候以"cc"为中心,向两边扩展,寻找最长的子字符串长度。
Java代码实现
public class Solution {
public String longestPalindrome(String s) {
if(s.length() <= 1)
return s;
int left = 0;int right = 0;
int len = s.length();
int max_len = 0;
int length = 0;
String res = "";
for(int i = 0; i < len; i++){
/*类似cabac情况,回文字符串长度为奇数*/
left = right = i;
while(left >= 0 && right < len && s.charAt(left) == s.charAt(right)){
left --;
right ++;
}
left++;right--;
//回文子字符串长度
length = right - left + 1;
//新得到的回文长度大于最长的回文长度,则替换为新的最长回文长度,同时更新最长的回文子字符串
if(length > max_len){
max_len = length;
res = s.substring(left , right + 1);
}
//向右扩展到字符串末尾,跳出循环
if(right == len -1)
break;
/*类似abba情况,回文字符串长度为偶数*/
left = i;
right = i + 1;
while(left >= 0 && right < len && s.charAt(left) == s.charAt(right)){
left --;
right ++;
}
left++;right--;
length = right - left + 1;
if(length > max_len){
max_len = length;
res = s.substring(left , right + 1);
}
if(right == len -1)
break;
}
return res;
}
}