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;
        }
    };
  • 相关阅读:
    windows 根据端口查看进行PID 并杀掉进程
    Linux下安装mysql-5.7
    springcloud参考视频和源码笔记
    idea中配置热部署
    技术/方案实现目录
    系统功能设计产出模版
    JQuery点击行tr实现checkBox选中与未选中切换
    Java学习第一天
    ES6 记录
    微信小程序记录
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/8978481.html
Copyright © 2011-2022 走看看