L2-008 最长对称子串 (25 分)

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 的反转函数判断是否对称,时间超限了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海边的宇航员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值