LeetCode 72 Edit Distance (C++, Python)

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character


Solution C++


 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
class Solution {
public:
    int minDistance(string word1, string word2) {
        int m = word1.size();
        int n = word2.size();
        if (m == 0) return n;
        if (n == 0) return m;
        vector<int> firstrow(n + 1, 0);
        iota(firstrow.begin(), firstrow.end(), 0);
        vector<int> secondrow(n + 1, 0);
        vector<int>* cur = &firstrow;
        vector<int>* prev = &secondrow;
        for (int i = 1; i <= m; ++i) {
            swap(prev, cur);
            for (int j = 0; j <= n; ++j) {
                if (j == 0) (*cur)[j] = i;
                else {
                    (*cur)[j] = min((*cur)[j - 1] + 1, (*prev)[j] + 1);
                    if (word1[i - 1] == word2[j - 1]) {
                        (*cur)[j] = min((*cur)[j], (*prev)[j - 1]);    
                    } else {
                        (*cur)[j] = min((*cur)[j], (*prev)[j - 1] + 1);
                    }
                }
            }
        }
        return (*cur).back();
    }
};

Solution Python


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    # @param {string} word1
    # @param {string} word2
    # @return {integer}
    def minDistance(self, word1, word2):
        m = len(word1)
        n = len(word2)
        cur = range(n + 1)
        prev = [0] * (n + 1)
        for i in range(1, m + 1):
            cur, prev = prev, cur
            for j in range(0, n + 1):
                if j == 0:
                    cur[j] = i
                else:
                    cur[j] = min(cur[j - 1] + 1, prev[j] + 1)
                    if word1[i - 1] == word2[j - 1]:
                        cur[j] = min(cur[j], prev[j - 1])
                    else:
                        cur[j] = min(cur[j], prev[j - 1] + 1)
        return cur[-1]

Popular posts from this blog

How Django Works (4) URL Resolution

Python Class Method and Class Only Method

How Django works (3): Testing Server and Static Files Serving