题解 | #公共子串计算#

公共子串计算

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;
    }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
10-04 05:12
瑞雪兆丰年_:可以贴个超级大的校徽,以防HR眼拙
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

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