48 lines
1.2 KiB
C++
48 lines
1.2 KiB
C++
#include <bits/stdc++.h>
|
|
|
|
using namespace std;
|
|
|
|
int memo[510][510];
|
|
|
|
int solve(string &w1, string &w2, int i = 0, int j = 0)
|
|
{
|
|
// all letters of w1 processed, we must add the remaining letters in w2
|
|
if (i >= w1.size())
|
|
{
|
|
return w2.size() - j;
|
|
}
|
|
// all letters of w2 processed, we must remove the left over letter in w1
|
|
if (j >= w2.size())
|
|
{
|
|
return w1.size() - i;
|
|
}
|
|
|
|
if (memo[i][j] != -1)
|
|
{
|
|
return memo[i][j];
|
|
}
|
|
|
|
// if letters are the same we just need to find the min number of operations
|
|
// for the remaining letters in w1 and w2
|
|
if (w1[i] == w2[j])
|
|
{
|
|
return memo[i][j] = solve(w1, w2, i + 1, j + 1);
|
|
}
|
|
|
|
// if letters are not the same we consider three cases
|
|
// 1. Deleting the current letter in w1
|
|
// 2. Replacing the current letter in w1 to be the same as the letter in w2
|
|
// 3. Inserting the current letter of w2 in w1 and continue with the same letters in w1
|
|
return memo[i][j] = min({solve(w1, w2, i + 1, j), solve(w1, w2, i + 1, j + 1), solve(w1, w2, i, j + 1)}) + 1;
|
|
}
|
|
|
|
int main()
|
|
{
|
|
int n, m;
|
|
cin >> n >> m;
|
|
string w1, w2;
|
|
cin >> w1 >> w2;
|
|
memset(memo, -1, sizeof(memo));
|
|
cout << solve(w1, w2) << endl;
|
|
return 0;
|
|
} |