题解 | #最长回文子串#

最长回文子串

https://www.nowcoder.com/practice/12e081cd10ee4794a2bd70c7d68f5507

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.hasNext()) { // 注意 while 处理多个 case
            String str = in.nextLine();
            int sum = 0;
            int[][] dp = new int[str.length()][str.length() / 2 + 1];
            int[][] dd = new int[str.length()][str.length() / 2 + 1];
            for (int i = 0; i < str.length(); i++) {
                dp[i][0] = 0;
            }
            for (int i = 0; i < str.length(); i++) {
                dd[i][0] = 1;
            }
            for (int i = 1; i < str.length() - 1; i++) {
                for (int j = 1; j < str.length() / 2+1; j++) {
                    if (i - j + 1 >= 0 && i + j < str.length() &&
                            str.charAt(i - j + 1) == str.charAt(i + j)) {
                        dp[i][j] = dp[i][j - 1] + 2;
                        sum = Math.max(dp[i][j], sum);
                    } else break;
                }
            }
            for (int i = 1; i < str.length() - 1; i++) {
                for (int j = 1; j < str.length() / 2+1; j++) {
                    if (i - j >= 0 && i + j < str.length() &&
                            str.charAt(i - j) == str.charAt(i + j)) {
                        dd[i][j] = dd[i][j - 1] + 2;
                        sum = Math.max(dd[i][j], sum);
                    } else break;
                }
            }
            System.out.println(sum);
        }
    }
}

全部评论

相关推荐

05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
找工作时遇到的神仙HR
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
昨天 14:10
啊啊啊啊好幸福,妈妈是我找工作发疯前的一束光
榕城小榕树:你是我见过最幸福的牛客男孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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