Skip to content

Commit 7457693

Browse files
authored
Create Longest common substring - DP.cpp
1 parent 08ec26c commit 7457693

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

Longest common substring - DP.cpp

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Dynamic programming solution
2+
#include <bits/stdc++.h>
3+
#include <ext/rope>
4+
using namespace std;
5+
using namespace __gnu_cxx;
6+
7+
using ld = long double;
8+
using llint = long long;
9+
using ullint = unsigned long long;
10+
using pii = pair <int,int>;
11+
using pcc = pair <char,char>;
12+
using pss = pair <string,string>;
13+
using vi = vector <int>;
14+
using vb = vector <bool>;
15+
using vii = vi::iterator;
16+
17+
#define INF (1<<30)
18+
#define MOD 1000000007
19+
#define mp make_pair
20+
#define mt make_tuple
21+
#define all(c) c.begin(), c.end()
22+
#define ms(name,val) memset(name, val, sizeof name)
23+
#define np nullptr
24+
25+
26+
int n, m;
27+
string a, b;
28+
vector <vi> DP;
29+
30+
int longestCommonSubstring()
31+
{
32+
int ans = 0;
33+
DP.resize(n);
34+
35+
for (int t1 = 0; t1 < n; ++t1)
36+
{
37+
DP[t1].resize(m);
38+
DP[t1][0] = (a[t1] == b[0]);
39+
}
40+
41+
for (int t2 = 0; t2 < m; ++t2)
42+
DP[0][t2] = (a[0] == b[t2]);
43+
44+
for (int t1 = 1; t1 < n; ++t1)
45+
{
46+
for (int t2 = 1; t2 < m; ++t2)
47+
{
48+
if (a[t1] == b[t2])
49+
{
50+
DP[t1][t2] = 1 + DP[t1-1][t2-1];
51+
ans = max(ans, DP[t1][t2]);
52+
}
53+
}
54+
}
55+
56+
return ans;
57+
}
58+
59+
int main()
60+
{
61+
ios_base::sync_with_stdio(0);
62+
//cin.tie(0);
63+
64+
cin >> a >> b;
65+
n = a.size(), m = b.size();
66+
cout << longestCommonSubstring() << '\n';
67+
68+
69+
return 0;
70+
}

0 commit comments

Comments
 (0)