8000 2 · javasharper/leetcode@cb66fb5 · GitHub
[go: up one dir, main page]

Skip to content

Commit cb66fb5

Browse files
committed
2
1 parent 24a32c9 commit cb66fb5

File tree

1 file changed

+17
-20
lines changed

1 file changed

+17
-20
lines changed

EditDistance/EditDistance.cpp

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,23 @@
11
class Solution {
22
public:
33
int minDistance(string word1, string word2) {
4-
// Start typing your C/C++ solution below
5-
// DO NOT write int main() function
6-
7-
int len1 = word1.size();
8-
int len2 = word2.size();
9-
10-
for (int i = 0; i <= max(len1, len2); i++)
11-
F[i][0] = F[0][i] = i;
12-
13-
for (int i = 1; i <= len1; i++) {
14-
for (int j = 1; j <= len2; j++) {
15-
if (word1[i-1] == word2[j-1])
16-
F[i][j] = F[i-1][j-1];
17-
else
18-
F[i][j] = min(F[i-1][j-1], min(F[i-1][j], F[i][j-1])) + 1;
4+
vector<vector<int>> dp(word1.size() + 1, vector<int>(word2.size() + 1, 0));
5+
for (int i = 1; i <= word1.size(); i++) {
6+
dp[i][0] = i;
7+
}
8+
for (int j = 1; j <= word2.size(); j++) {
9+
dp[0][j] = j;
10+
}
11+
for (int i = 1; i <= word1.size(); i++) {
12+
for (int j = 1; j <= word2.size(); j++) {
13+
if (word1[i-1] == word2[j-1]) {
14+
dp[i][j] = dp[i-1][j-1];
15+
} else {
16+
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + 1;
17+
dp[i][j] = min(dp[i][j], dp[i-1][j-1] + 1);
18+
}
1919
}
2020
}
21-
return F[len1][len2];
21+
return dp[word1.size()][word2.size()];
2222
}
23-
private:
24-
static const int MAXN = 1010;
25-
int F[MAXN][MAXN];
26-
};
23+
};

0 commit comments

Comments
 (0)
0