NC127 最长公共子串

最长公共子串

https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac?tpId=188&&tqId=38644&rp=1&ru=/ta/job-code-high-week&qru=/ta/job-code-high-week/question-ranking

二刷

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) {
        int len1 = str1.length();
        int len2 = str2.length();

        int[][] dp = new int[len1+1][len2+1];
        int maxindex = 0;
        int max = 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;
                    if(dp[i][j] > max){
                        max = dp[i][j];
                        maxindex = i-1;
                    }
                }   
                else
                    dp[i][j] = 0;
            }
        }

        String res_s = str1.substring(maxindex-max+1,maxindex+1);
        return res_s;


    }
}

动态规划
建立一个二维数组
首先初始化第一行和第一列
接下来 状态转移方程
dp[i][j] = dp[i-1][j-1] +1;

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) {
        int maxLenth = 0;//记录最长公共子串的长度
        int maxLastIndex = 0;
        int[][] dp = new int[str1.length()][str2.length()];
        int i,j;
        // 初始化
        for(i=0,j=0;i<str1.length();i++){
            if(str1.charAt(i) == str2.charAt(j)){
                dp[i][j] = 1;
            }
            else{dp[i][j] = 0;}
        }
        for(i=0,j=0;j<str2.length();j++){
            if(str1.charAt(i) == str2.charAt(j)){
                dp[i][j] = 1;
            }
            else{dp[i][j] = 0;}
        }
        // 更新
        for(i=1;i<str1.length();i++){
            for(j=1;j<str2.length();j++){
                if(str1.charAt(i) == str2.charAt(j)){
                    dp[i][j] = dp[i-1][j-1] +1;
                    if(dp[i][j] > maxLenth){
                        maxLenth = dp[i][j];
                        maxLastIndex = i;
                    }
                }else{
                    dp[i][j] = 0;
                }
            }
        }
        return str1.substring(maxLastIndex + 1 -  maxLenth, maxLastIndex+1);

    }
}

2.最长公共子序列 待续。。。

面试题解 文章被收录于专栏

面试题解

全部评论

相关推荐

美团 客服平台 薪资应该是后端算高的了,我们姑且称为nk了,给3w签字费
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务