给定两个只包含小写字母的字符串,计算两个字符串的最大公共子串的长度。

公共子串计算

http://www.nowcoder.com/questionTerminal/98dc82c094e043ccb7e0570e5342dd1b

import java.util.Scanner;

public class Main {

public static void main(String[] args) {

    Scanner scanner = new Scanner(System.in);

    String nextLine = scanner.nextLine();
    String nextLine1 = scanner.nextLine();

    String lStr = nextLine.length() > nextLine1.length() ? nextLine : nextLine1;
    String sStr = nextLine.length() < nextLine1.length() ? nextLine : nextLine1;

    int max = 0;
    for (int i = 0; i < sStr.length(); i++) {
        for (int j = i + 1; j <= sStr.length(); j++) {
            String substring = sStr.substring(i, j);
            if (lStr.contains(substring)) {
                max = substring.length() > max ? substring.length() : max;
            }
        }
    }
    System.out.println(max);
}

}

全部评论
暴力的话可以在if语句加一个else{break;}提高效率
点赞 回复
分享
发布于 2021-06-10 18:44
lStr==sStr的情况没有考虑
点赞 回复
分享
发布于 2021-09-04 16:32
联易融
校招火热招聘中
官网直投

相关推荐

7 1 评论
分享
牛客网
牛客企业服务