自己写的。是不是和之前的某道题目重复了?

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

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

import java.util.Scanner;


public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String str1 = in.nextLine();
            String str2 = in.nextLine();
            if (str2.length() < str1.length()) {
                String temp = str1;
                str1 = str2;
                str2 = temp;
            }
            int n = str1.length();
            int max = 0;
            int start = 0;
            for (int i = 1; i <= n; i++) {
                for (int j = 0; j <= n - i; j++) {
                    for (int k = j; k <= n - i; k++) {
                        String sub = str1.substring(k, k + i);
                        if (str2.contains(sub) && i > max) {
                            max = i;
                            start = k;
                        }
                    }
                }
            }
            System.out.println(str1.substring(start, start + max));
        }
    }
}

全部评论

相关推荐

11-15 18:39
已编辑
西安交通大学 Java
全村最靓的仔仔:卧槽,佬啥bg呢,本也是西交么
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务