You are given two strings, A and B. Answer, what is the smallest number of operations you need to
transform A to B?
Operations are:
- Delete one letter from one of strings
- Insert one letter into one of strings
- Replace one of letters from one of strings with another letter
Input
T - number of test cases
For each test case:
String A
String B
Both strings will contain only uppercase characters and they won't
be longer than 2000 characters.
There will be 10 test cases in data set.
Output
For each test case, one line, minimum number of operations.
Example
Input:
1
FOOD
MONEY
Output:
4
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int LevenshteinDistance(string s, string t) {
if (s == t) {
return 0;
} else if (s.size() == 0) {
return t.size();
} else if (t.size() == 0) {
return s.size();
}
vector<int> v0 = vector<int> (t.size() + 1),
v1 = vector<int> (t.size() + 1);
for (int i = 0; i < v0.size(); ++i) {
v0[i] = i;
}
for (int i = 0; i < s.size(); ++i) {
v1[0] = i + 1;
for (int j = 0; j < t.size(); ++j) {
int cost = (s[i] == t[j] ? 0 : 1);
v1[j + 1] = min(min(v1[j] + 1, v0[j + 1] + 1),
v0[j] + cost);
}
v0 = v1;
}
return v1[t.size()];
}
int main() {
int T;
cin >> T;
for (;T--;) {
string a,b;
cin >> a >> b;
cout << LevenshteinDistance(a, b) << "\n";
}
return 0;
}