-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestcommonsubstring.cpp
More file actions
53 lines (49 loc) · 953 Bytes
/
longestcommonsubstring.cpp
File metadata and controls
53 lines (49 loc) · 953 Bytes
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
#include <limits.h>
#include <iostream>
#include <vector>
using namespace std;
void print(vector<vector<int>> &dp, int i, int j, char *x, char *y)
{
if (i > j) return ;
if (x[i-1] == y[j-1])
{
print(dp, i - 1, j - 1, x, y);
cout<<x[i-1];
}
}
int lcs(char *x, char *y, int n, int m)
{
vector<vector<int>> dp(n+1, vector<int>(m+1));
int max = -1;
int start, end;
for (int i = 0; i <= n; ++i)
{
for (int j = 0; j <= m; ++j)
{
if (i == 0 || j == 0)
dp[i][j] = 0;
else if (x[i - 1] == y[j - 1])
{
dp[i][j] = dp[i-1][j-1] + 1;
if(max < dp[i][j])
{
max = dp[i][j];
start = i;
end = j;
}
}
}
}
print(dp, start, end, x, y);
return max;
}
int main()
{
char X[] = "OldSite:GeeksforGeeks.org";
char Y[] = "NewSite:GeeksQuiz.com";
int m = strlen(X);
int n = strlen(Y);
cout <<endl<< "Length of Longest Common Substring is " << lcs(X, Y, m, n);
getchar();
return 0;
}