题解 | #公共子串计算#,怎么记得之前有一道一样的

公共子串计算

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNext()) { // 注意 while 处理多个 case
            String str1 = in.next();
            String str2 = in.next();
            int length1 = str1.length();
            int length2 = str2.length();
            int result ;
            if (length1 <= length2) {
                result = getMaxStr(str1, str2);
            } else {
                result = getMaxStr(str2, str1);
            }
            System.out.println(result);
        }
    }

    private static int getMaxStr(String str1, String str2) {
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();
        int length1 = chars1.length;
        int maxLength = 0;
        for (int i = 0; i < length1; i++) {
            char c1 = chars1[i];
            int length2 = chars2.length;
            for (int j = 0; j < length2; j++) {
                char c2 = chars2[j];
                if (c2 == c1) {
                    int count = 1;
                    for (int x = i + 1, y = j + 1; x < length1 && y < length2; x++, y++) {
                        if (chars1[x] == chars2[y]) {
                            count++;
                            continue;
                        }
                        break;
                    }
                    maxLength = Math.max(maxLength, count);
                }
            }
        }
        return maxLength;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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