forked from sachuverma/DataStructures-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Edit Distance.cpp
75 lines (60 loc) · 1.57 KB
/
Edit Distance.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
Edit Distance
=============
Given two strings s and t. Find the minimum number of operations that need to be performed on str1 to convert it to str2. The possible operations are:
Insert
Remove
Replace
Example 1:
Input:
s = "geek", t = "gesek"
Output: 1
Explanation: One operation is required
inserting 's' between two 'e's of str1.
Example 2:
Input :
s = "gfg", t = "gfg"
Output:
0
Explanation: Both strings are same.
Your Task:
You don't need to read or print anything. Your task is to complete the function editDistance() which takes strings s and t as input parameters and returns the minimum number of operation required to make both strings equal.
Expected Time Complexity: O(|s|*|t|)
Expected Space Complexity: O(|s|*|t|)
Constraints:
1 <= Length of both strings <= 100
Both the strings are in lowercase.
*/
int Min(int x, int y, int z) { return min(min(x, y), z); }
int editDist(string str1, string str2, int m, int n, vector<vector<int>> &dp)
{
if (dp[m][n] != -1)
return dp[m][n];
if (m == 0)
{
dp[m][n] = n;
return n;
}
if (n == 0)
{
dp[m][n] = m;
return m;
}
if (str1[m - 1] == str2[n - 1])
{
int ans = editDist(str1, str2, m - 1, n - 1, dp);
dp[m][n] = ans;
return ans;
}
int ans = 1 + Min(editDist(str1, str2, m, n - 1, dp), editDist(str1, str2, m - 1, n, dp), editDist(str1, str2, m - 1, n - 1, dp));
dp[m][n] = ans;
return ans;
}
int editDistance(string s, string t)
{
int m = s.size(), n = t.size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1, -1));
editDist(s, t, m, n, dp);
return dp[m][n];
;
}