题解 | #公共子串计算#

公共子串计算

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

import java.util.Objects;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        // Scanner in = new Scanner(System.in);
        // while (in.hasNextLine()) {
        //     String nextLine = in.nextLine();
        //     if (Objects.isNull(nextLine) || nextLine.equals("")) {
        //         break;
        //     }
        //     String nextLine1 = in.nextLine();
        //     // 先dp找出最长的长度
        //     // aaabc
        //     // baaabbc
        //     int[][] dp = new int[nextLine.length() + 1][nextLine1.length() + 1];
        //     int max = 0;
        //     String maxStr = "";
        //     for (int i = 1; i <= nextLine.length(); i++) {
        //         for (int j = 1; j <= nextLine1.length(); j++) {
        //             // 假设字符串1的第i个字符和字符串2的第j个字符一致,那么他们的最大dp值为 各自当前字符串长度-1后的dp值+1
        //             if (nextLine.charAt(i - 1) == nextLine1.charAt(j - 1)) {
        //                 dp[i][j] = dp[i - 1][j - 1] + 1;
        //                 if (dp[i][j] > max) {
        //                     max = dp[i][j];
        //                     maxStr = nextLine1.substring(j - max, j);
        //                 }
        //             } else {
        //                 // 当发现不等于时,说明断开了,需要从0开始计算,这一步非常关键!
        //                 dp[i][j] = 0;
        //             }

        //         }
        //     }
        //     System.out.println(maxStr.length());
        // }

        Scanner in = new Scanner(System.in);
        while (in.hasNextLine()) {
            String nextLine = in.nextLine();
            if (Objects.isNull(nextLine) || nextLine.equals("")) {
                break;
            }
            String nextLine1 = in.nextLine();
            String max = (nextLine.length() > nextLine1.length()) ? nextLine : nextLine1;
            String min = (nextLine.length() > nextLine1.length()) ? nextLine1 : nextLine;
            // 用游标循环的方式解决问题
            // i是右侧的游标
            for (int i = 0; i < min.length(); i++) {
                // j是左侧的游标
                for (int j = 0, k = min.length() - i; k <= min.length(); j++, k++) {
                    if (max.contains(min.substring(j, k))) {
                        System.out.println(min.substring(j, k).length());
                        return;
                    }
                }
            }
             System.out.println(0);
        }
    }
}

全部评论

相关推荐

双尔:你就写拥有ai开发经历,熟练运用提示词,优化ai,提高ai回答质量
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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