Skip to content

Commit 069ea6b

Browse files
authored
Merge pull request #299 from KeerthanaPravallika/KeerthanaPravallika
Added Longest Common Substring program (in cpp)
2 parents 01bd65e + 0a66a3a commit 069ea6b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
Given two strings. The task is to find the length of the longest common substring.
3+
*/
4+
5+
#include<bits/stdc++.h>
6+
using namespace std;
7+
8+
class Solution{
9+
public:
10+
11+
int longestCommonSubstr (string s1, string s2, int n, int m)
12+
{
13+
int len_subs[n+1][m+1];
14+
int i,j,maxLength=0;
15+
16+
for(i=0;i<=n;i++)
17+
len_subs[i][0] = 0; //first row
18+
19+
for(i=0;i<=m;i++)
20+
len_subs[0][i] = 0; // first column
21+
22+
for(i = 1;i<=n;i++)
23+
{
24+
for(j=1;j<=m;j++)
25+
{
26+
if(s1[i-1] == s2[j-1])
27+
{
28+
len_subs[i][j] = 1 + len_subs[i-1][j-1];
29+
if(maxLength < len_subs[i][j])
30+
maxLength = len_subs[i][j];
31+
}
32+
else
33+
len_subs[i][j] = 0;
34+
}
35+
}
36+
return maxLength;
37+
}
38+
};
39+
int main()
40+
{
41+
int t; cin >> t;
42+
while (t--)
43+
{
44+
int n, m; cin >> n >> m;
45+
string s1, s2;
46+
cin >> s1 >> s2;
47+
Solution ob;
48+
49+
cout << ob.longestCommonSubstr (s1, s2, n, m) << endl;
50+
}
51+
}

0 commit comments

Comments
 (0)