题解 | #公共子串计算#

公共子串计算

https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b

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()) { // 注意 while 处理多个 case
            String line1 = in.nextLine();
            String line2 = in.nextLine();
            if(line1.length()>line2.length()) {
                String c = line1;
                line1 = line2;
                line2 = c;
            }
            int maxLen =0;
            int[][]dp = new int[line1.length()+1][line2.length()+1];
            for(int i=1;i<=line1.length();i++) {
                for(int j=1;j<=line2.length();j++) {
                    if(line1.charAt(i-1) == line2.charAt(j-1)) {
                        dp[i][j] = dp[i-1][j-1] + 1;
                        maxLen = Math.max(maxLen, dp[i][j]);
                    }
                }
            }
            System.out.println(maxLen);
        }
    }
}

全部评论

相关推荐

06-12 16:00
天津大学 Java
牛客30236098...:腾讯坏事做尽,终面挂是最破防的 上次被挂了后我连简历都不刷了
点赞 评论 收藏
分享
06-27 18:53
门头沟学院 Java
这样才知道自己不适合搞代码,考公去咯
只爱喝白开水:我也发现不适合搞代码,打算转非技术方向了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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