题解 | #查找两个字符串a,b中的最长公共子串#

查找两个字符串a,b中的最长公共子串

http://www.nowcoder.com/practice/181a1a71c7574266ad07f9739f791506

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String str1 = sc.nextLine();//短串
            String str2 = sc.nextLine();//长串
            if(str1.length()>str2.length()){
                String temp=str1;
                str1=str2;
                str2=temp;
            }
            char[] chars1 = str1.toCharArray();
            char[] chars2 = str2.toCharArray();
           
            int[][] dp = new int[chars1.length + 1][chars2.length + 1];
            int max = 0;
            for (int i = 1; i <= chars1.length; i++) {
                for (int j = 1; j <= chars2.length; j++) {
                    if (chars1[i - 1] != chars2[j - 1]) continue;
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    max = Math.max(dp[i][j], max);
                }
            }
            int signal=0;
            for (int i = 1; i <= chars1.length; i++) {                
                for (int j = 1; j <= chars2.length; j++) {
                    if(max == dp[i][j] && signal==0){
                        signal=1;
                        System.out.println(str1.substring(i-max,i));
                    } 
                }
            }
        }
    }
}
全部评论

相关推荐

头像
11-07 01:12
重庆大学 Java
精致的小松鼠人狠话不多:签哪了哥
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务