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

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

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

import java.util.Scanner;

public class Main {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner scan = new Scanner(System.in);
    while (scan.hasNext()) {
        String str1 = scan.next();
        String str2 = scan.next();

        String shortStr = str1.length() <= str2.length() ? str1 : str2;
        String longStr = str1.length() <= str2.length() ? str2 : str1;

        int shortLen = shortStr.length();
        int maxLen = 0;
        String retStr = "";

        for (int i = 0; i < shortLen; i++) {
            if (shortLen - i <= maxLen) {
                break;
            }
            for (int b = i, k = shortLen; k - b > maxLen; k--) {
                String sub = shortStr.substring(b, k);
                if (longStr.contains(sub) && sub.length() > maxLen) {
                    maxLen = sub.length();
                    retStr = sub;
                    break;
                }
            }
        }

        System.out.println(retStr);
    }

}

}

全部评论

相关推荐

10-30 10:16
南京大学 Java
龚至诚:给南大✌️跪了
点赞 评论 收藏
分享
object3:开始给部分🌸孝子上人生第一课了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务