-
Notifications
You must be signed in to change notification settings - Fork 353
/
Copy pathLongest_common_substring.cpp
51 lines (44 loc) · 1.15 KB
/
Longest_common_substring.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
/*
Given two strings. The task is to find the length of the longest common substring.
*/
#include<bits/stdc++.h>
using namespace std;
class Solution{
public:
int longestCommonSubstr (string s1, string s2, int n, int m)
{
int len_subs[n+1][m+1];
int i,j,maxLength=0;
for(i=0;i<=n;i++)
len_subs[i][0] = 0; //first row
for(i=0;i<=m;i++)
len_subs[0][i] = 0; // first column
for(i = 1;i<=n;i++)
{
for(j=1;j<=m;j++)
{
if(s1[i-1] == s2[j-1])
{
len_subs[i][j] = 1 + len_subs[i-1][j-1];
if(maxLength < len_subs[i][j])
maxLength = len_subs[i][j];
}
else
len_subs[i][j] = 0;
}
}
return maxLength;
}
};
int main()
{
int t; cin >> t;
while (t--)
{
int n, m; cin >> n >> m;
string s1, s2;
cin >> s1 >> s2;
Solution ob;
cout << ob.longestCommonSubstr (s1, s2, n, m) << endl;
}
}