zoukankan      html  css  js  c++  java
  • 72. Edit Distance

    https://leetcode.com/problems/edit-distance/description/

    DP

    class Solution {
    public:
        int minDistance(string word1, string word2) {
            int m = word1.length(), n = word2.length();
            vector<vector<int>> dp(m+1, vector<int>(n+1, INT_MAX));
            for (int i = 0; i <= m; i++)
                dp[i][0] = i;
            for (int j = 0; j <= n; j++)
                dp[0][j] = j;
            for (int i = 1; i <= m; i++)
                for (int j = 1; j <= n; j++) {
                    if (word1[i-1] == word2[j-1])
                        dp[i][j] = dp[i-1][j-1];
                    else
                        dp[i][j] = min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j])) + 1;
                }
            return dp[m][n];
        }
    };

    递归 (bad performance, should change cache key to index [i,j] in the two words)

    class Solution {
    public:
        map<pair<string,string>, int> cache;
        int minDistance(string word1, string word2) {
            auto key = make_pair(word1, word2);
            if (cache.count(key))   return cache[key];
                
            if (word1 == word2) return 0;
            int idx = 0;
            while (word1[idx] == word2[idx])    idx++;
            if (idx == word1.length())  return word2.length() - idx;
            if (idx == word2.length())  return word1.length() - idx;
            int res = 1 + min(
                minDistance(word1.substr(idx+1),word2.substr(idx+1)),    // replace current
                min(
                    minDistance(word1.substr(idx+1),word2.substr(idx)),  // delete one from first
                    minDistance(word1.substr(idx),word2.substr(idx+1))   // delete one from second
                ));
            cache[key] = res;
            return res;
        }
    };
  • 相关阅读:
    kafka在线修改topic配置
    DateFormat采坑
    mysql ifnull 取反值;case when null的使用
    pip常用命令
    zip压缩
    Solaris 10 x86-64 虚拟机配置
    正则学习
    vnc
    window10创建系统服务
    java内存对象clone
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/8978481.html
Copyright © 2011-2022 走看看