-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path30_LongestCommonSubstring.cpp
112 lines (96 loc) · 2.79 KB
/
30_LongestCommonSubstring.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// https://www.codingninjas.com/codestudio/problems/longest-common-substring_1235207?leftPanelTab=0
// You have been given two strings 'STR1' and 'STR2'. You have to find the length of the
// longest common substring.
// A string “s1” is a substring of another string “s2” if “s2” contains the same characters
// as in “s1”, in the same order and in continuous fashion also.
#include <bits/stdc++.h>
using namespace std;
class Solution_
{
// Print the longest common substring - FollowUp
public:
int longestCommonSubsequence(string text1, string text2)
{
int n1 = text1.size(), n2 = text2.size();
vector<vector<int>> dp(n1 + 1, vector<int>(n2 + 1, 0));
int ans = INT_MIN;
int x, y;
for (int i = 1; i <= n1; ++i)
{
for (int j = 1; j <= n2; ++j)
{
if (text1[i - 1] == text2[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1];
else dp[i][j] = 0;
if (ans < dp[i][j]) {
ans = dp[i][j];
x = i;
y = j;
}
}
}
int len = ans;
string lcs(len, '_');
while (x && y && dp[x][y]) {
lcs[--len] = text1[x-1];
--x, --y;
}
cout << lcs;
return 0;
}
};
class Solution1
{
// Space Optmised
public:
int longestCommonSubsequence(string text1, string text2)
{
int n1 = text1.size(), n2 = text2.size();
vector<vector<int>> dp(n1 + 1, vector<int>(n2 + 1, 0));
vector<int> curr(n2+1), temp(n2+1);
int ans = INT_MIN;
for (int i = 1; i <= n1; ++i)
{
for (int j = 1; j <= n2; ++j)
{
if (text1[i - 1] == text2[j - 1])
temp[j] = 1 + curr[j - 1];
else
temp[j] = 0;
ans = max(ans, temp[j]);
}
curr = temp ;
}
return ans;
}
};
class Solution
{
public:
int longestCommonSubsequence(string text1, string text2)
{
int n1 = text1.size(), n2 = text2.size();
vector<vector<int>> dp(n1 + 1, vector<int>(n2 + 1, 0));
int ans = INT_MIN;
for (int i = 1; i <= n1; ++i)
{
for (int j = 1; j <= n2; ++j)
{
if (text1[i - 1] == text2[j - 1])
dp[i][j] = 1 + dp[i - 1][j - 1];
else
dp[i][j] = 0;
ans = max(ans, dp[i][j]);
}
}
return ans;
}
};
int main()
{
string text1 = "apple", text2 = "rampageapple";
Solution1 Obj1;
Obj1.longestCommonSubsequence(text1, text2);
ios_base::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}