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.
public class Solution {
public String longestPalindrome(String s) {
boolean flag[][] = new boolean[s.length()][s.length()];//标记i到j之间的子串是否为回文
int max = 0;
int start = 0;a
int end = 0;
for(int i=0;i<s.length();i++){//单个字符为回文
flag[i][i] = true;
}
for(int j=1;j<s.length();j++){
for(int i=0;i<j;i++){
if(s.charAt(i)==s.charAt(j)){//如果i,j上字符相同,也就是说第一个和最后一个相同;不相同就是可以判断不是回文了
if(i+1>j-1||flag[i+1][j-1])//如果i+1>j-1也就是i,j相邻,说明是回文,另外,如果i+1,j-1之间为回文,则判断为回文
flag[i][j] = true;
if(flag[i][j]&&max<j-i+1){
start = i;
end = j;
max = j-i+1;
}
}
}
}
return s.substring(start, end+1);
}
}