# 5.最长回文字串

class Solution {
public String longestPalindrome(String s) {
// Insert '#'
String t = "\$#";
for (int i = 0; i < s.length(); ++i) {
t += s.charAt(i);
t += "#";
}
t += "@";
// Process t
int[] p = new int[t.length()];;
int mx = 0, id = 0, resLen = 0, resCenter = 0;
for (int i = 1; i < t.length()-1; ++i) {
p[i] = mx > i ? Math.min(p[2 * id - i], mx - i) : 1;
while (((i - p[i])>=0) && ((i + p[i])<t.length()-1) && (t.charAt(i + p[i]) == t.charAt(i - p[i])))
++p[i];
if (mx < i + p[i]) {
mx = i + p[i];
id = i;
}
if (resLen < p[i]) {
resLen = p[i];
resCenter = i;
}
}
return s.substring((resCenter - resLen) / 2, (resCenter - resLen) / 2 + resLen-1);

}
}


class Solution {

public static String longestPalindrome(String s) {
if(s == null || s.length() == 0){
return "";
}
int[] range = new int[2];
char[] str = s.toCharArray();
for(int i = 0 ; i <  s.length(); i ++){
i = findLongest(str,i,range);
}
return s.substring(range[0],range[1]+1);
}
public static int findLongest(char[] str, int low, int[] range){
int high = low ;
while (high < str.length - 1 && str[high + 1] == str[low]){
high ++ ;
}
int ans = high;
while (low > 0 && high < str.length - 1 && str[low -1] == str[high + 1]){
low --;
high ++;
}
if(high - low > range[1] - range[0]){
range[0] = low;
range[1] = high;
}
return ans;
}
}