Leetcode[583] Delete Operation for Two Strings

This problem is the same as finding the longest common subsequence of two strings.

Solution 1 (Recursion, TLE)
class Solution {
public:
    int minDistance(string word1, string word2) {
        int commonLen = LCS(word1, word2);
        int n = word1.length();
        int m = word2.length();
        return n + m - 2*commonLen;
    }
    
    int LCS(string s1, string s2) {
        if(s1.empty() || s2.empty()) return 0;
        int n = s1.length();
        int m = s2.length();
        if(s1[n-1] == s2[m-1]) return 1 + LCS(s1.substr(0, n-1), s2.substr(0, m-1));
        else return max(LCS(s1.substr(0, n-1), s2), LCS(s1, s2.substr(0, m-1)));
    }
};

This solution is TLE. Not sure if the algorithm is wrong.
update
The algorithm is correct, but it does not have the memorization part, so it basically requires computing the subproblem repeatedly, thus results in TLE.

Solution 2 (DP with memorization)
class Solution {
public:
    int minDistance(string word1, string word2) {
        int commonLen = LCS(word1, word2);
        int n = word1.length();
        int m = word2.length();
        return n + m - 2*commonLen;
    }
    
    int LCS(string s1, string s2) {
        int n = s1.length();
        int m = s2.length();
        vector<vector<int>> res(n+1, vector<int>(m+1, 0));
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= m; j++) {
                if(s1[i-1] == s2[j-1]) res[i][j] = 1 + res[i-1][j-1];
                else res[i][j] = max(res[i-1][j], res[i][j-1]);
            }
        }
        return res[n][m];
    }
};

Same idea as the recursive solution, but this one is accepted.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 2017年8月25日 星期五 天气晴 今天是辅导班结束暑假班的日子,不知不觉孩子们的暑假也已经到了尾...
    金腾岳妈妈阅读 1,432评论 0 1
  • Today is Thursday. The next few stories are really strang...
    Mr_Oldman阅读 1,171评论 0 0
  • 今早又开始做养生操了。 马步压腿和闭眼金鸡独立后,开始绕手腕。 转呀转的,才转那么几下,赫然发现右手腕比之前大有不...
    若水柳柳柳阅读 4,943评论 0 0
  • 前阵子,在基友的推荐下,爱上了深夜食堂,那僻静的店铺,简朴的食材,滋滋作响的回忆味道,细腻绵长。 厚蛋烧,茶泡饭,...
    多肉是个好菇凉阅读 4,969评论 16 8

友情链接更多精彩内容