Skip to content

Commit a5c15c9

Browse files
authored
Merge pull request #43 from vipu18/patch-4
Implement edit distance algorithm with optimization
2 parents aa383ee + ceb2463 commit a5c15c9

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <iostream>
2+
#include <vector>
3+
#include <string>
4+
using namespace std;
5+
6+
// Space Optimization version
7+
class Solution {
8+
public:
9+
int editDistance(string start, string target) {
10+
int n = start.size();
11+
int m = target.size();
12+
vector<int> prev(m + 1, 0), curr(m + 1, 0);
13+
for (int j = 0; j <= m; j++) prev[j] = j;
14+
for (int i = 1; i <= n; i++) {
15+
curr[0] = i;
16+
for (int j = 1; j <= m; j++) {
17+
if (start[i - 1] == target[j - 1])
18+
curr[j] = prev[j - 1];
19+
else
20+
curr[j] = 1 + min(prev[j - 1], min(curr[j - 1], prev[j]));
21+
}
22+
prev = curr;
23+
}
24+
return curr[m];
25+
}
26+
};
27+
28+
int main() {
29+
string s1, s2;
30+
cout << "Enter first string: ";
31+
cin >> s1;
32+
cout << "Enter second string: ";
33+
cin >> s2;
34+
Solution sol;
35+
int result = sol.editDistance(s1, s2);
36+
cout << "Edit Distance: " << result << endl;
37+
return 0;
38+
}

0 commit comments

Comments
 (0)