题解 | 公共子串计算

公共子串计算

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);
        String s = in.nextLine();
        String t = in.nextLine();
        // 2. 初始化 DP 表
        // dp[i][j] 表示 s 的前 i 个字符和 t 的前 j 个字符的最长公共后缀长度
        // 为了方便,我们让 dp 数组的索引从 1 开始对应字符串的字符
        int[][] dp = new int[s.length() + 1][t.length() + 1];

        // 用于记录最长公共子串的长度
        int maxLength = 0;

        for (int i = 1; i <= s.length(); i++) {
            for (int j = 1; j <= t.length(); j++) {
                if (s.charAt(i-1) == t.charAt(j-1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    if (dp[i][j] > maxLength) {
                        maxLength = dp[i][j];
                    }
                }

            }
        }
        System.out.print(maxLength);

    }
}

全部评论

相关推荐

09-29 00:03
门头沟学院 Java
点赞 评论 收藏
分享
10-24 11:08
已编辑
上海大学 Java
TTT___TTT:这个价是前端吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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