题解 | 密码截取

密码截取

https://www.nowcoder.com/practice/3cd4621963e8454594f00199f4536bb1

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) {
            String str = in.nextLine();
            int n = str.length();
            int max = 0;

            for (int l = 0; l < n - 1; l++) {
                for (int r = 1; r < n; r++) {
                    if (l < r && str.charAt(l) == str.charAt(r) &&
                            str.substring(l, r).contentEquals(
                                new StringBuilder(str.substring(l + 1,
                                                  r + 1)).reverse())) { // 比如ABBA, ABB和BBA的反转比较相同即回文
                        max = Math.max(str.substring(l, r + 1).length(), max);
                    }
                    if (l > r && str.charAt(l) == str.charAt(r) &&
                            str.substring(r, l).contentEquals(
                                new StringBuilder(str.substring(r + 1,
                                                  l + 1)).reverse())) { // 比如ABBA, ABB和BBA的反转比较相同即回文
                        max = Math.max(str.substring(r, l + 1).length(), max);
                    }
                }
            }
            System.out.println(max);
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务