|
| 1 | +/** |
| 2 | +Given two strings word1 and word2, return the minimum number of operations required to convert word1 to word2. |
| 3 | +
|
| 4 | +You have the following three operations permitted on a word: |
| 5 | +
|
| 6 | +Insert a character |
| 7 | +Delete a character |
| 8 | +Replace a character |
| 9 | + |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +
|
| 13 | +Input: word1 = "horse", word2 = "ros" |
| 14 | +Output: 3 |
| 15 | +Explanation: |
| 16 | +horse -> rorse (replace 'h' with 'r') |
| 17 | +rorse -> rose (remove 'r') |
| 18 | +rose -> ros (remove 'e') |
| 19 | +Example 2: |
| 20 | +
|
| 21 | +Input: word1 = "intention", word2 = "execution" |
| 22 | +Output: 5 |
| 23 | +Explanation: |
| 24 | +intention -> inention (remove 't') |
| 25 | +inention -> enention (replace 'i' with 'e') |
| 26 | +enention -> exention (replace 'n' with 'x') |
| 27 | +exention -> exection (replace 'n' with 'c') |
| 28 | +exection -> execution (insert 'u') |
| 29 | +**/ |
| 30 | + |
| 31 | +class Solution { |
| 32 | +public: |
| 33 | + int minDistance(string word1, string word2) { |
| 34 | + int m = word1.size(); // source |
| 35 | + int n = word2.size(); // destination |
| 36 | + |
| 37 | + if(m == 0 && n == 0) return 0; |
| 38 | + int dp[501][501] = {0}; |
| 39 | + |
| 40 | + int i, j; // iterators |
| 41 | + for(i = 1; i <=m; ++i) { |
| 42 | + dp[0][i] = i; |
| 43 | + } |
| 44 | + for(i = 1; i <=n;++i) { |
| 45 | + dp[i][0] = i; |
| 46 | + } |
| 47 | + for(i = 1; i <=n; ++i) { |
| 48 | + for(int j = 1; j <= m; ++j) { |
| 49 | + if(word1[j-1] == word2[i-1]) |
| 50 | + dp[i][j] = dp[i-1][j-1]; |
| 51 | + else { |
| 52 | + dp[i][j] = 1 + min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j])); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + return dp[n][m]; |
| 57 | + } |
| 58 | +}; |
0 commit comments