题解 | #最长公共子串# DP

最长公共子串

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * longest common substring
     * @param str1 string字符串 the string
     * @param str2 string字符串 the string
     * @return string字符串
     */
    public String LCS (String str1, String str2) {
        // write code here
        
        int len1 = str1.length();
        int len2 = str2.length();
        int dp[][] = new int[len1+1][len2+1];
        int max = 0;
        int max_i = 0, max_j = 0;
        for(int i=1;i<=len1;i++){
            for(int j=1;j<=len2;j++){
                if(str1.charAt(i-1) == str2.charAt(j-1)){
                    dp[i][j] = dp[i-1][j-1] + 1;
                }else{
                    dp[i][j] = 0;
                }
                if(dp[i][j] > max){
                    max = dp[i][j];
                    max_i = i;
                    max_j = j;
                }
            }
        }
        return str1.substring(max_i - max , max_i );
    }
}

通用的最长公共子串解法中,求解的是最长公共子串的长度,我们可以同时记录下来,获取到最大长度时候的下标,然后进行截取,该方法只适用于最长公共子串(连续),对于最长公共子序列(不连续)不成立。

全部评论

相关推荐

下北澤大天使:你是我见过最美的牛客女孩😍
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
06-11 13:34
offe从四面八方来:我真的没时间陪你闹了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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