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

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

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        String s=in.nextLine();
        String t=in.nextLine();

        //dp[i][j]->s的第1到i位和t的第1到j位中的最长公共子串
        int[][] dp=new int[s.length()+1][t.length()+1];
        for(int i=1;i<=s.length();i++){
            for(int j=1;j<=t.length();j++){
                if(s.charAt(i-1)==t.charAt(j-1)){
                    dp[i][j]=dp[i-1][j-1]+1;
                }else{
                    dp[i][j]=0;
                }
            }
        }

        int res=0;
        int indexI=0;
        int indexJ=0;
        for(int i=1;i<=s.length();i++){
            for(int j=1;j<=t.length();j++){
                if(dp[i][j]>res){
                    res=dp[i][j];
                    indexI=i;
                    indexJ=j;
                }else if(dp[i][j]==res){
                    indexI=Math.min(i,indexI);
                    indexJ=Math.min(j,indexJ);
                }
            }
        }
        if(s.length()<t.length()){
            System.out.println(s.substring(indexI-res,indexI));
        }else{
             System.out.println(t.substring(indexJ-res,indexJ));
        }
    }
}

如果存在多个最长公共子串,输出在较短串中最先出现的那个。

全部评论

相关推荐

02-11 14:29
已编辑
字节跳动_QA
Edgestr:这种的写代码最狠了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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