Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 769617d

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 887c77f commit 769617d

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

‎0072_edit_distance/edit_distance.cc‎

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,27 @@ using namespace std;
55
class Solution {
66
public:
77
int minDistance(string word1, string word2) {
8-
vector<vector<int>> dp;
9-
for (int i = 0; i <= word1.length(); i++) {
10-
dp.push_back(vector<int>(word2.length() + 1));
11-
dp[i][0] = i;
12-
}
13-
for (int i = 0; i <= word2.length(); i++) {
14-
dp[0][i] = i;
8+
int l1 = word1.length();
9+
int l2 = word2.length();
10+
vector<int> dp(l2 + 1);
11+
for (int i = 0; i <= l2; i++) {
12+
dp[i] = i;
1513
}
1614

17-
for (int i = 1; i <= word1.length(); i++) {
18-
for (int j = 1; j <= word2.length(); j++) {
15+
int up = 0;
16+
for (int i = 1; i <= l1; i++) {
17+
int left_up = dp[0];
18+
dp[0] = i;
19+
for (int j = 1; j <= l2; j++) {
20+
up = dp[j];
1921
if (word1[i - 1] == word2[j - 1]) {
20-
dp[i][j] = dp[i - 1][j - 1];
22+
dp[j] = left_up;
2123
} else {
22-
dp[i][j] = 1 + min(dp[i - 1][j - 1], min(dp[i - 1][j], dp[i][j - 1]));
24+
dp[j] = 1 + min(left_up, min(up, dp[j - 1]));
2325
}
26+
left_up = up;
2427
}
2528
}
26-
27-
return dp[word1.length()][word2.length()];
29+
return dp[l2];
2830
}
2931
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /