题目
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.
思路
该问题可以采用自里向外的方法,因为我们知道,假如字符串S是回文串,则xSx也是回文串
代码
public class Solution {
public String longestPalindrome(String s) {
String result = "";
int len = s.length();
for(int i=0; i<len; i++){
int m, n;
m = n = i;
while(m>=0 && n<len){
if(s.charAt(m) == s.charAt(n)){
m--;
n++;
}else break;
}
if(result.length() < n-m-1) result = s.substring(m+1, n);
m = i;
n = i + 1;
while(m>=0 && n<len){
if(s.charAt(m) == s.charAt(n)){
m--;
n++;
}else break;
}
if(result.length() < n-m-1) result = s.substring(m+1, n);
}
return result;
}
}