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

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

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

import java.util.Scanner;

public class Main {
    // abcdefghijklmnop
    // abcsafjklmnopqrstuvw
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String  a = in.nextLine();
            String  b = in.nextLine();

            int longLength = 0;
            int shortLength = 0;
            String origin = null;
            String model = null;

            if (b.length() > a.length()) {
                shortLength = a.length();
                longLength = b.length();
                origin = b;
                model = a;
            } else {
                shortLength = b.length();
                longLength = a.length();
                origin = a;
                model = b;
            }

            int max = 0;
            String result = "";
            for (int j = 0; j < shortLength; j++) {
                // 逐个匹配
                for (int i = 0; i < longLength; i++) {
                    int temp = 0;
                    int y = i, z = j;
                    while (y < longLength && z < shortLength) {
                        if (origin.charAt(y) == model.charAt(z)) {
                            temp++;
                            z++;
                            y++;
                        } else {
                            break;
                        }

                    }
                    if (temp > max) {
                        result = model.substring(j, j + temp);
                        max = temp;
                    }
                }
            }
            System.out.println(result);

        }
    }
}

全部评论

相关推荐

06-19 13:40
武汉大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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