题解 | 最长公共子串

最长公共子串

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

#include <iterator>
#include <string>
#include <vector>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * longest common subsequence
     * @param s1 string字符串 the string
     * @param s2 string字符串 the string
     * @return string字符串
     */
    string LCS(string s1, string s2) {
        // write code here
        if (s1.empty() || s2.empty()) {
            return "-1";
        }

        int n = s1.size();
        int m = s2.size();
        s1 = " " + s1;
        s2 = " " + s2;


        int maxlen = INT_MIN;
        int endindex = 0;
        vector<vector<int>> dp(n + 1, vector<int> (m + 1, 0));
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= m; j++) {
                if (s1[i] == s2[j]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    if (dp[i][j] > maxlen) {
                        maxlen = dp[i][j];
                        endindex = i;
                    }

                } else {
                    dp[i][j] = 0;
                }

            }
        }

        // 提取最长公共子串
        string result = s1.substr(endindex - maxlen + 1, maxlen);
        return result;
    }
};

全部评论

相关推荐

缒梦&独舞:这家公司是这样的,去年给我实习offer了,不过也是面着玩儿的,他周六还要去做公益志愿活动
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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