题解 | #最长公共子串#

最长公共子串

https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac

import java.util.*;


public class Solution {
   
   //dp[i][j]表示字符串1前i个和字符串2前j个中最长公共子串,注意的说,我们子串连续
    public static String LCS (String str1, String str2) {
        // write code here
        //1.建表
        int n = str1.length(),m = str2.length();
        String[][] dp = new String[n+1][m+1]; //虚拟节点设为空即可
        for(int i=0;i<=n;i++){
            for(int j=0;j<=m;j++){
                dp[i][j] = "";
            }
        }

        String longstr = "";
        //2.填表 ,分为当前位置字符相同和当前位置字符不同

        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                if(str1.charAt(i-1)==str2.charAt(j-1)){
                    dp[i][j] = dp[i-1][j-1] +str1.charAt(i-1);
                    longstr = dp[i][j].length() > longstr.length()  ? dp[i][j] :longstr;
                }else{
                    //不相同时,就为空,子串需要连续,
                    dp[i][j] = "";
                }
            }
        }

        
        return longstr;
    }
}

全部评论

相关推荐

06-17 21:57
门头沟学院 Java
白友:噗嗤,我发现有些人事就爱发这些,明明已读不回就行了,就是要恶心人
点赞 评论 收藏
分享
07-23 11:23
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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