Skip to content

Commit a453d3e

Browse files
refactor 72
1 parent ea1f8a9 commit a453d3e

File tree

1 file changed

+34
-31
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+34
-31
lines changed

src/main/java/com/fishercoder/solutions/_72.java

Lines changed: 34 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -2,48 +2,51 @@
22

33
/**
44
* 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.)
69
710
You have the following 3 operations permitted on a word:
811
912
a) Insert a character
1013
b) Delete a character
11-
c) Replace a character*/
14+
c) Replace a character
15+
*/
1216

1317
public class _72 {
1418

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[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();
3531

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);
4147
}
42-
table[i][j] = Math.min(Math.min(table[i - 1][j] + 1, table[i][j - 1] + 1), table[i - 1][j - 1] + cost);
4348
}
49+
return table[m][n];
4450
}
45-
46-
return table[m][n];
4751
}
48-
4952
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy