C++ solution in 11 lines


  • 0
    P
    int minDistance(string word1, string word2) {
        vector<int> cur(word2.size() + 1, 0), prev;
        for (int i = 0; i <= word2.size(); ++i) cur[i] = i;
        for (int i = 1; i <= word1.size(); ++i) {
            prev = cur;
            cur[0] = i;
            for (int j = 1; j <= word2.size(); ++j) {
                if (word1[i - 1] == word2[j - 1]) cur[j] = prev[j - 1];
                else cur[j] = min(min(prev[j - 1], prev[j]), cur[j - 1]) + 1;
            }
        }
        return cur[word2.size()];
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.