L2-008 最长对称子串 (25 分)##
对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。
输入格式:
输入在一行中给出长度不超过1000的非空字符串。
输出格式:
在一行中输出最长对称子串的长度。
输入样例:
Is PAT&TAP symmetric?
输出样例:
11
package highLadder;
import java.io.*;
import java.util.StringTokenizer;
/**
* @author hang
* @create 2022-03-12 13:34
*/
public class L2008 {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
static PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
public static void main(String[] args) throws IOException {
String line = reader.readLine();
int max = 1;
for (int i = line.length() - 1; i > 0; i --) {
for (int j = 0; j < i; j ++) {
if (line.charAt(i) == line.charAt(j) ) {
int k = 0;
for ( k = j; k <= i ; k ++) {
if (line.charAt(k) != line.charAt(i - (k-j))) {
break;
}
}
if (k == i + 1) {
max = Math.max(max, i - j + 1);
}
}
if (i - j + 1 < max) {
break;
}
}
}
System.out.print(max);
}
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(reader.readLine());
}
return tokenizer.nextToken();
}
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
static double nextDoule() throws IOException {
return Double.parseDouble(next());
}
static long nextLong() throws IOException {
return Long.parseLong(next());
}
}
题目本身不难,暴力三层for循环,注意点 刚开始用StringBuild 的反转函数判断是否对称,时间超限了