题解 | #公共子串计算#

公共子串计算

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

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();

        int res;
        if (s1.length() < s2.length()) {
            res = method(s1, s2);
        } else res = method(s2, s1);
        System.out.println(res);
    }

    private static int method(String shortString, String longString) {
        int count = 0;
        int res = 0;
        for (int i = 0; i < shortString.length(); i++) {
            String sub = shortString.substring(i);
            for (int j = 0; j < longString.length(); j++) {
                int curIndex = j;
                for (int k = 0; k < sub.length(); k++) {
                    if (curIndex >= longString.length()) break;
                    if (longString.charAt(curIndex) == sub.charAt(k)) {
                        curIndex++;
                        count++;
                    } else break;
                }
                res = Math.max(count, res);
                count = 0;
            }
        }
        return res;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
04-30 18:05
空屿编号:你把墨镜摘下来是不是这样😭
点赞 评论 收藏
分享
05-29 20:08
西南大学 golang
Euchimegle:MySOL是什么
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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