Skip to content

Commit 1bc6ec1

Browse files
committed
Time: 4 ms (93.13%), Space: 6.6 MB (90.99%) - LeetHub
1 parent 2931cd3 commit 1bc6ec1

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

0072-edit-distance/0072-edit-distance.cpp

+37-1
Original file line numberDiff line numberDiff line change
@@ -85,12 +85,48 @@ class Solution {
8585
return dp[0][0];
8686
}
8787

88+
int solveSpc(string str1, string str2, int len1, int len2) {
89+
if(len1 == 0) return len2;
90+
if(len2 == 0) return len1;
91+
92+
vector<int> curr(len2+1, 0);
93+
vector<int> next(len2+1, 0);
94+
95+
for(int j=0; j<len2; j++) {
96+
next[j] = len2 - j;
97+
}
98+
99+
for(int i=len1-1; i>=0; i--) {
100+
for(int j=len2-1; j>=0; j--) {
101+
curr[len2] = len1 - i;
102+
int ans = 0;
103+
104+
if(str1[i] == str2[j]) {
105+
ans = next[j+1];
106+
} else {
107+
int insAns = 1 + curr[j+1];
108+
int delAns = 1 + next[j];
109+
int repAns = 1 + next[j+1];
110+
111+
ans = min(insAns, min(delAns, repAns));
112+
}
113+
114+
curr[j] = ans;
115+
}
116+
next = curr;
117+
}
118+
119+
return next[0];
120+
}
121+
88122
int minDistance(string word1, string word2) {
89123
// return solveRec(word1, word2, 0, 0);
90124

91125
// vector<vector<int>> dp(word1.length(), vector<int>(word2.length(), -1));
92126
// return solveMem(dp, word1, word2, 0, 0);
93127

94-
return solveTab(word1, word2, word1.length(), word2.length());
128+
// return solveTab(word1, word2, word1.length(), word2.length());
129+
130+
return solveSpc(word1, word2, word1.length(), word2.length());
95131
}
96132
};

0 commit comments

Comments
 (0)