|
2 | 2 |
|
3 | 3 | /**
|
4 | 4 | * 72. Edit Distance
|
5 |
| - * 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.) |
| 5 | + * |
| 6 | + * Given two words word1 and word2, |
| 7 | + * find the minimum number of steps required to convert word1 to word2. |
| 8 | + * (each operation is counted as 1 step.) |
6 | 9 |
|
7 | 10 | You have the following 3 operations permitted on a word:
|
8 | 11 |
|
9 | 12 | a) Insert a character
|
10 | 13 | b) Delete a character
|
11 |
| - c) Replace a character*/ |
| 14 | + c) Replace a character |
| 15 | + */ |
12 | 16 |
|
13 | 17 | public class _72 {
|
14 | 18 |
|
15 |
| - public int minDistance(String word1, String word2) { |
16 |
| - int m = word1.length(); |
17 |
| - int n = word2.length(); |
18 |
| - if (m == 0) { |
19 |
| - return n; |
20 |
| - } |
21 |
| - if (n == 0) { |
22 |
| - return m; |
23 |
| - } |
24 |
| - |
25 |
| - char[] str1 = word1.toCharArray(); |
26 |
| - char[] str2 = word2.toCharArray(); |
27 |
| - |
28 |
| - int[][] table = new int[m + 1][n + 1]; |
29 |
| - for (int i = 0; i < m + 1; i++) { |
30 |
| - table
10000
[i][0] = i; |
31 |
| - } |
32 |
| - for (int j = 0; j < n + 1; j++) { |
33 |
| - table[0][j] = j; |
34 |
| - } |
| 19 | + public static class Solution1 { |
| 20 | + public int minDistance(String word1, String word2) { |
| 21 | + int m = word1.length(); |
| 22 | + int n = word2.length(); |
| 23 | + if (m == 0) { |
| 24 | + return n; |
| 25 | + } |
| 26 | + if (n == 0) { |
| 27 | + return m; |
| 28 | + } |
| 29 | + char[] str1 = word1.toCharArray(); |
| 30 | + char[] str2 = word2.toCharArray(); |
35 | 31 |
|
36 |
| - for (int i = 1; i < m + 1; i++) { |
37 |
| - for (int j = 1; j < n + 1; j++) { |
38 |
| - int cost = 0; |
39 |
| - if (str1[i - 1] != str2[j - 1]) { |
40 |
| - cost = 1; |
| 32 | + int[][] table = new int[m + 1][n + 1]; |
| 33 | + for (int i = 0; i < m + 1; i++) { |
| 34 | + table[i][0] = i; |
| 35 | + } |
| 36 | + for (int j = 0; j < n + 1; j++) { |
| 37 | + table[0][j] = j; |
| 38 | + } |
| 39 | + for (int i = 1; i < m + 1; i++) { |
| 40 | + for (int j = 1; j < n + 1; j++) { |
| 41 | + int cost = 0; |
| 42 | + if (str1[i - 1] != str2[j - 1]) { |
| 43 | + cost = 1; |
| 44 | + } |
| 45 | + table[i][j] = Math.min(Math.min(table[i - 1][j] + 1, table[i][j - 1] + 1), |
| 46 | + table[i - 1][j - 1] + cost); |
41 | 47 | }
|
42 |
| - table[i][j] = Math.min(Math.min(table[i - 1][j] + 1, table[i][j - 1] + 1), table[i - 1][j - 1] + cost); |
43 | 48 | }
|
| 49 | + return table[m][n]; |
44 | 50 | }
|
45 |
| - |
452B
46 |
| - return table[m][n]; |
47 | 51 | }
|
48 |
| - |
49 | 52 | }
|
0 commit comments