Skip to content

Instantly share code, notes, and snippets.

@zhanggang807
Created October 4, 2018 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhanggang807/05ece8e5a8e1d1008c901c5a9afa426a to your computer and use it in GitHub Desktop.
Save zhanggang807/05ece8e5a8e1d1008c901c5a9afa426a to your computer and use it in GitHub Desktop.
最长回文子串算法
public class Manacher{
public static void main(String[] args) {
String line = "ababbbb";
System.out.println("最大回文子串: "+Manacher(line));
}
public static String Manacher(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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment