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.
String
Solution in Java:
public class Solution {
public String longestPalindrome(String s) {
int len = s.length();
if(len<2) return s;
boolean[][] opj = new boolean[len][len];
//opj[i][j] denotes if s[i...j] is a palindromic, so we have i<=j and opj[m][m]=true(0<=m<len)
for(int m=0; m<len; m++) opj[m][m] = true;
int max = 0, start = 0;
for(int j=1; j<len; j++){
for(int i=0; i<j; i++){
if(s.charAt(i)==s.charAt(j)){
//special cases:
//j>i, so j-i>0. for j-i=1, opj[i][j]=true for s[i]=s[j]
// for j-i=2, i+1=j-1, so opj[i][j]=opj[i+1][j-1]=true
if(i+1>j-1) opj[i][j] = true;
else opj[i][j] = opj[i+1][j-1];
if(opj[i][j]&&j-i+1>max){
max = j-i+1;
start = i;
}
}
else opj[i][j] = false; //s[i]!=s[j] then opj[i][j] = false
}
}
return s.substring(start, start+max);
//Note that shoud be substring(start, start+max), not substring(start, max)
//in Java, substring(startIndex, endIndex), the second parameter is the end position
//(not include the last character in substring),
//so that endIndex-startIndex is the length of substring, which is max in this case.
}
}