最长对称子串
对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串
输出格式:
在一行中输出最长对称子串的长度
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
String s = br.readLine();
int max = 1;
for (int i = 1; i < s.length() - max / 2; ++i) {
int index = 0;
int num = 0;
while (i - 1 - index >= 0 && i + index < s.length() && s.charAt(i + index) == s.charAt(i - 1 - index)) {
num += 2;
index++;
}
max = max > num ? max : num;
num = 1;
while (i - 2 - index >= 0 && i + index < s.length() && s.charAt(i + index) == s.charAt(i - 2 - index)) {
num += 2;
index++;
}
max = max > num ? max : num;
}
out.print(max);
out.flush();
}
}