-
Notifications
You must be signed in to change notification settings - Fork 0
/
LongestCommonSubstring.cpp
51 lines (43 loc) · 1.11 KB
/
LongestCommonSubstring.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
// Longest Common Substring
// Given two strings. The task is to find the length of the longest common substring.
// { Driver Code Starts
#include<bits/stdc++.h>
using namespace std;
// } Driver Code Ends
class Solution{
public:
int longestCommonSubstr (string S1, string S2, int n, int m)
{
// your code here
int res = 0;
int dp[n + 1][m + 1];
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(S1[i - 1] == S2[j - 1]){
dp[i][j] = 1 + dp[i - 1][j - 1];
res = max(res, dp[i][j]);
}else{
dp[i][j] = 0;
}
}
}
return res;
}
};
// { Driver Code Starts.
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;
}
}
// Contributed By: Pranay Bansal
// } Driver Code Ends