Leetcode-72

Edit Distance

Time complexity: $O(mn)$

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <cstring>
#include <vector>
#include <numeric>

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

Leetcode-72

Licensed under CC BY-NC-SA 4.0