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) {
if(s.length() < 2)
return s;
int len = s.length();
String maxSub = "";
int maxLen = 0;
for(int i = 0; i < len; ++i){
String tempOdd = expandPalindrome(s, i, i);
if(maxLen < tempOdd.length()) {
maxSub = tempOdd;
maxLen = tempOdd.length();
}
if(i + 1 < len) {
String tempEven = expandPalindrome(s, i , i + 1);
if(maxLen < tempEven.length()) {
maxSub = tempEven;
maxLen = tempEven.length();
}
}
}
return maxSub;
}
private String expandPalindrome(String s, int left, int right){
int len = s.length();
while(left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
--left;
++right;
}
return s.substring(left + 1, right);
}
}