Suppose we have two words S and T, we have to find the minimum number of operations needed to convert from S to T. The operations can be of three types, these are
- insert a character,
- delete a character
- replace a character.
So if the input strings are “evaluate” and “fluctuate”, then the result will be 5.
To solve this, we will follow these steps −
n := size of s, m := size of t,
create an array dp of size n + 1
for i in range 0 to n
dp[i] := new array of size m + 1
for j in range 0 to m:
dp[i, j] := 0
if i = 0, then dp[i,j] = j
otherwise when j = 0, then dp[i, j] := i
s := blank space and concatenate s, t := blank space and concatenate t
for i in range 1 to n
for j in range 1 to m
if s[i] is not t[j], then dp[i, j] := 1 + min of dp[i – 1, j], dp[i, j - 1], dp[i – 1, j – 1]
otherwise dp[i, j] := dp[i – 1, j – 1]
return dp[n, m]
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int minDistance(string s, string t) {
int n = s.size();
int m =t.size();
int** dp = new int*[n+1];
for(int i =0;i<=n;i++){
dp[i] = new int[m+1];
for(int j=0;j<=m;j++){
dp[i][j]=0;
if(i==0)dp[i][j]=j;
else if(j==0)dp[i][j] = i;
}
}
s = " " + s;
t = " " + t;
for(int i =1;i<=n;i++){
for(int j = 1;j<=m;j++){
if(s[i] !=t[j]){
dp[i][j] = 1+min({dp[i-1][j],dp[i][j-1],dp[i-1][j-1]});
}else{
dp[i][j] = dp[i-1][j-1];
}
}
}
return dp[n][m];
}
};
main(){
Solution ob;
cout << (ob.minDistance("fluctuate", "evaluate"));
}Input
"fluctuate" "evaluate"
Output
5