File tree 1 file changed +56
-0
lines changed
1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Problem : A substring of a string is a subsequence in which all the characters are consecutive.Given two strings,
2
+ // we need to find the longest common substring.
3
+
4
+ // Approach :
5
+
6
+ // We are creating a 2d dp array corresponding to the dimensions of the array. Now if the characters for a pair of
7
+ // i, j are not equal, that show that they can be included in the final answer and hence they are discarded.
8
+ // Else, we take a look at dp[i-1][j-1] if the continuity is maintained the we can find a continous equal substring
9
+ // or not.
10
+
11
+ #include < bits/stdc++.h>
12
+ using namespace std ;
13
+
14
+ int lcs (string &s1, string &s2)
15
+ {
16
+ int n = s1.size ();
17
+ int m = s2.size ();
18
+ vector<vector<int >> dp (n + 1 , vector<int >(m + 1 , 0 ));
19
+ int ans = 0 ;
20
+ for (int i = 1 ; i <= n; i++)
21
+ {
22
+ for (int j = 1 ; j <= m; j++)
23
+ {
24
+ if (s1[i - 1 ] == s2[j - 1 ])
25
+ {
26
+ // looking if just previous characters are also equal or not
27
+ int val = 1 + dp[i - 1 ][j - 1 ];
28
+ dp[i][j] = val;
29
+ ans = max (ans, val);
30
+ }
31
+ else
32
+ {
33
+ // not a part of equal substring, hence 0
34
+ dp[i][j] = 0 ;
35
+ }
36
+ }
37
+ }
38
+ return ans;
39
+ }
40
+
41
+ int main ()
42
+ {
43
+ string s1;
44
+ string s2;
45
+ cin >> s1 >> s2;
46
+ cout << " The Length of Longest Common Substring is " << lcs (s1, s2);
47
+ }
48
+
49
+ // Sample Inputs
50
+
51
+ // abcjklp
52
+ // acjkp
53
+
54
+ // Corresponding Outputs
55
+
56
+ // 3
You can’t perform that action at this time.
0 commit comments