Leetcode Edit Distance
Two strings to determine the editing distance between them. You can delete, add, and replace them in three operations. For each operation, the distance is incremented by one. For example, the distance between "AB" and "abc" is 1. Dynamic Planning: use dis [I] [j] to record the distance between the first I of string1 and the first j of string2. So we can know: 1. if the I of str1, that is, str1 [I-1] is equal to the j of str2, that is, str2 [J-1, so dis [I] [j] = dis [I-1] [J-1] 2. if str [I-1]! = Str2 [J-1] 2.1 replace str [I-1] With str2 [J-1] By replacement, then dis [I] [j] = dis [I-1] [J-1] + 1; 2.2 inserting str2 [J-1] After str1 through the insert operation is equivalent to calculating dis [I] [j] = dis [I] [J-1] + 1; 2.3 Insert str1 [I-1] After str2 through the insert operation, that is, dis [I] [j] = dis [I-1] [j] + 1; select the smallest of the three. Iterative update. The Code is as follows: copy the code class Solution {public: int minDistance (string word1, string word2) {int len1 = word1.size (), len2 = word2.size (); if (len1 = 0) return len2; if (len2 = 0) return len1; vector <int> dis (len1 + 1, vector <int> (len2 + 1 )); for (int I = 0; I <= len1; ++ I) {dis [I] [0] = I;} for (int j = 1; j <= len2; ++ j) {dis [0] [j] = j ;}for (int I = 1; I <= len1; ++ I) for (int j = 1; j <= len2; ++ j) {If (word1 [I-1]! = Word2 [j-1]) {dis [I] [j] = min (dis [I-1] [J-1] + 1, dis [I-1] [j] + 1 ); dis [I] [j] = min (dis [I] [J-1] + 1, dis [I] [j]);} else dis [I] [j] = dis [I-1] [J-1];} return dis [len1] [len2];};