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

最长公共子串

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

using System;
using System.Collections.Generic;


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[] dp = new int [str2.Length + 1];
        int ansStart = -1, ansCount = 0;
        for(int i = 1; i <= str1.Length; i++){
            for(int j = str2.Length; j >= 1; j--){
                if(str1[i - 1] == str2[j - 1]){
                    dp[j] = dp[j - 1] + 1;
                    if(dp[j] > ansCount){
                        ansCount = dp[j];
                        ansStart = j - ansCount;
                    }
                }
                else dp[j] = 0;
            }
        }
        return ansCount > 0 ? str2.Substring(ansStart, ansCount) : "";
    }
}

全部评论

相关推荐

MingoTree:看不出你你的技术栈,想找什么工作,然后课设项目别写上去了,自我评价删了,前后端你想好你要干啥,这种简历投上去秒挂的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务