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

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

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

import java.util.Scanner;

// 两层for循环,遍历所有子串
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String s1 = in.nextLine();
        String s2 = in.nextLine();
        String sortS = s1;
        String longS = s2;
        String res = "";
        if (s1.length() > s2.length()) {
            sortS = s2;
            longS = s1;
        }
        for (int i = 0; i < sortS.length(); i++) {
            for (int j = 0; j < sortS.length() - i; j++) {
                if (longS.contains(sortS.substring(i, sortS.length() - j))) {
                    if(sortS.substring(i, sortS.length() - j).length() > res.length())
                        res = sortS.substring(i, sortS.length() - j);
                }
            }
        }
        System.out.println(res);
    }
}

全部评论

相关推荐

04-18 15:58
已编辑
门头沟学院 设计
kaoyu:这一看就不是计算机的,怎么还有个排斥洗碗?
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务