-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path133_longest_common_substring.cpp
More file actions
56 lines (53 loc) · 933 Bytes
/
Copy path133_longest_common_substring.cpp
File metadata and controls
56 lines (53 loc) · 933 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
54
55
56
// https://practice.geeksforgeeks.org/problems/longest-common-substring/0
#include <bits/stdc++.h>
using namespace std;
int lcs(string a, string b, int n, int m)
{
vector< vector<int> > L(n, vector<int>(m));
int max_length = 0;
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
// corner case
if (i == 0 || j == 0)
{
if (a[i] == b[j])
L[i][j] = 1;
else
L[i][j] = 0;
}
else
{
if (a[i] == b[j])
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = 0;
}
if (L[i][j] > max_length)
max_length = L[i][j];
}
}
// print_2d(L);
return max_length;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while (t--)
{
int n, m;
cin >> n >> m;
string a, b;
cin >> a >> b;
cout << lcs(a, b, n, m) << endl;
}
return 0;
}