题解 | 公共子串计算

公共子串计算

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

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str1 = in.nextLine();
        String str2 = in.nextLine();

        String strShort = str1.length() <=
                str2.length() ? str1 : str2;
        String strLong = str1.length() >
                str2.length() ? str1 : str2;

        int count = 0;
        if (strLong.contains(strShort)) {
            System.out.println(strShort.length());
            return;
        }

        for (int i = 0; i < strShort.length() - 2; i++) {
            for (int j = i+1; j < strShort.length() - 1; j++) {
                if (strLong.contains(strShort.substring(i,j))) {
                    count = Math.max(count, j-i);
                }
            }
        }
        System.out.println(count);
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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