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.
Analysis: Find even and odd palindromic string separately.
public class Solution {
public String helper(int left, int right, int size, String s) {
while(left>=0 && right<=size-1) {
if(s.charAt(left)!=s.charAt(right)) break;
left--;
right++;
}
return s.substring(left+1, right);
}
public String longestPalindrome(String s) {
int size = s.length();
if(size==0) return "";
String res = "";
// even palindrome
for(int i=0; i<size; i++) {
String temp1 = helper(i, i, size, s);
if(temp1.length()>res.length()) res=temp1;
}
// odd palindrome
for(int j=0; j<size-1; j++) {
String temp2 = helper(j, j+1, size, s);
if(temp2.length()>res.length()) res=temp2;
}
return res;
}
}