Title: |
Edit Distance |
Pass Rate: |
26.1% |
Difficulty: |
Difficult |
Given 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
The topic is the classic problem of dynamic programming, the formula is as follows:
1, S1.length==0,return s2.length;
2, S2.length==0,return s1.length;
3. If S1.charat (i) ==s2.charat (j), Res[i][j]=res[i-1][j-1]
else Res[i][j]=min (res[i-1][j],res[i][j-1],res[i-1][i-1]+1)
See the code specifically:
1 Public classSolution {2 Public intmindistance (String word1, String word2) {3 intLen1 =word1.length ();4 intLen2 =word2.length ();5 6 //len1+1, len2+1, because finally return DP[LEN1][LEN2]7 int[] DP =New int[Len1 + 1] [Len2 + 1];8 9 for(inti = 0; I <= len1; i++) TenDp[i][0] =i; One A for(intj = 0; J <= Len2; J + +) -DP[0][J] =J; - the - //iterate though, and check last char - for(inti = 1; I <= len1; i++) { - CharC1 = Word1.charat (i-1); + for(intj = 1; J <= Len2; J + +) { - CharC2 = Word2.charat (j-1); + A //if last chars equal at if(C1 = =C2) { - //Update DP value for +1 length -DP[I][J] = dp[i-1][j-1]; -}Else { - intReplace = Dp[i-1][j-1] + 1; - intInsert = Dp[i-1][j] + 1; in intDelete = Dp[i][j-1] + 1; - to intMin =math.min (replace, insert); +Min =math.min (min,delete); -DP[I][J] =min; the } * } $ }Panax Notoginseng - returnDp[len1][len2]; the } +}
Leetcode------Edit Distance