最长回文子串

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1088

回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。
输入一个字符串Str,输出Str里最长回文子串的长度。

Input

输入Str(Str的长度 <= 1000)

Output

输出最长回文子串的长度L。

Input示例

daabaac

Output示例

5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StreamTokenizer;

public class {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
while (in.nextToken() != StreamTokenizer.TT_EOF) {
String s1 = in.sval;
out.println(Manacher(s1));
}
out.flush();
}

static int Manacher(String str) {
String s = "$#";
for (int i = 0; i < str.length(); i++) {
s += str.charAt(i) + "#";
}
int max = 0;
int id = 0;
int[] p = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
int maxLen = p[id] + id;
if (maxLen > i) {
p[i] = Math.min(p[2 * id - i], maxLen - i);
}
while (i + p[i] < s.length() && i - p[i] >= 0 && s.charAt(i - p[i]) == s.charAt(i + p[i])) {
p[i]++;
}
if (maxLen < i + p[i]) {
id = i;
}
max = Math.max(max, p[i]);
}
return max - 1;
}
}