题解 | #查找两个字符串a,b中的最长公共子串#

查找两个字符串a,b中的最长公共子串

https://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str_1 = in.nextLine();
        String str_2 = in.nextLine();

        int len_1 = str_1.length();
        int len_2 = str_2.length();

        if(len_1 < len_2){
            System.out.print(sub(str_1,str_2));
        }
        else{
            System.out.print(sub(str_2,str_1));
        }
    }

    private static String sub(String str_1, String str_2) {

        int len_1 = str_1.length();
        int len_2 = str_2.length();

        int index = 0;
        int max = 0;

        int[][] dp = new int[len_1 + 1][len_2 + 2];
        for (int i = 1; i <= len_1; i++) {
            for (int j = 1; j <= len_2; j++) {
                if (str_1.charAt(i - 1) == str_2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    if (dp[i][j] > max) {
                        max = dp[i][j];
                        index = i;
                    }
                }
            }
        }

        return str_1.substring(index - max, index);
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务