题解 | #公共子串计算#

公共子串计算

https://www.nowcoder.com/practice/98dc82c094e043ccb7e0570e5342dd1b

求解最大公共子串:从较短字符串开始,截取不同长度、不同位置的子串,判断长字符串是否包含。

import java.util.*;

public class Main {
    public static void main(String[] args)  {
        Scanner scan=new Scanner(System.in);
        String input1=scan.nextLine();
        String input2=scan.nextLine();

        if(input1.length()<=input2.length()){
            System.out.println(result(input1,input2));
        }else{
            System.out.println(result(input2,input1));
        }

    }

    //求解最大公共子串长度,str1<str2长度
    public static int result(String str1,String str2){
        for(int i=str1.length();i>=0;i--){//子串的长度
            for(int j=0;j<=str1.length()-i;j++){//开始截取子串的位置
                String sub=str1.substring(j,j+i);
                if(str2.contains(sub)) return sub.length();
            }
        }
        return 0;
    }
}
全部评论

相关推荐

11-04 10:30
已编辑
门头沟学院 研发工程师
开心小狗🐶:“直接说答案”
点赞 评论 收藏
分享
11-11 16:40
已编辑
门头沟学院 人工智能
不知道怎么取名字_:这个有点不合理了,相当于已经毕业了,但还是没转正,这不就是白嫖
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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