File tree Expand file tree Collapse file tree 2 files changed +112
-0
lines changed
Expand file tree Collapse file tree 2 files changed +112
-0
lines changed Original file line number Diff line number Diff line change 1+ /* *
2+ * @author:divyakhetan
3+ * @date: 3/1/2019
4+ */
5+
6+
7+
8+ #include < bits/stdc++.h>
9+ using namespace std ;
10+
11+ int main () {
12+ string s1,s2;
13+ cin >> s1 >> s2;
14+
15+ int n = s1.length ();
16+ int m = s2.length ();
17+
18+ int lcs[n + 1 ][m + 1 ];
19+
20+ int ma = 0 ;
21+ int mi = 0 ;
22+ int mj = 0 ;
23+ for (int i =0 ; i <=n; i++){
24+ for (int j = 0 ; j <=m;j++){
25+ if (i == 0 || j == 0 ) lcs[i][j] = 0 ;
26+ else if (s1[i -1 ] == s2[j - 1 ]){
27+ lcs[i][j] = 1 + lcs[i - 1 ][j - 1 ];
28+ if (lcs[i][j] > ma){
29+ mi = i;
30+ mj = j;
31+ ma = lcs[i][j];
32+ }
33+
34+ }
35+ else {
36+ lcs[i][j]= 0 ;
37+ }
38+ }
39+ }
40+ int i = 0 ;
41+ int j = 0 ;
42+ string ans= " " ;
43+ for (i=mi, j=mj; i>=0 ; i--, j--) {
44+ if (!(i<=0 || j<=0 ) && lcs[i][j] != 0 ) {
45+ ans += s1[i-1 ];
46+ } else {
47+ break ;
48+ }
49+ }
50+ reverse (ans.begin (), ans.end ());
51+ cout << " len : " << ma << " is " << ans;
52+ }
Original file line number Diff line number Diff line change @@ -88,3 +88,63 @@ function longestSubstring (str1, str2) {
8888console .log (longestSubstring (" abcdefg" , " xyabcz" ));
8989console .log (longestSubstring (" XYXYXYZ" , " XYZYX" ));
9090```
91+
92+
93+ ## C++ Implementation
94+
95+ ### [ Solution using dynamic programming] ( ./C++/longestCommonSubstringday11.cpp )
96+
97+ ``` cpp
98+ /* *
99+ * @author:divyakhetan
100+ * @date: 3/1/2019
101+ */
102+
103+
104+
105+ #include < bits/stdc++.h>
106+ using namespace std ;
107+
108+ int main () {
109+ string s1,s2;
110+ cin >> s1 >> s2;
111+
112+ int n = s1.length();
113+ int m = s2.length();
114+
115+ int lcs[ n + 1] [ m + 1 ] ;
116+
117+ int ma = 0;
118+ int mi = 0;
119+ int mj = 0;
120+ for(int i =0; i <=n; i++){
121+ for(int j = 0; j <=m;j++){
122+ if(i == 0 || j == 0) lcs[ i] [ j ] = 0;
123+ else if(s1[ i -1] == s2[ j - 1] ){
124+ lcs[ i] [ j ] = 1 + lcs[ i - 1] [ j - 1 ] ;
125+ if(lcs[ i] [ j ] > ma){
126+ mi = i;
127+ mj = j;
128+ ma = lcs[ i] [ j ] ;
129+ }
130+
131+ }
132+ else{
133+ lcs[ i] [ j ] = 0;
134+ }
135+ }
136+ }
137+ int i = 0;
138+ int j = 0;
139+ string ans= "";
140+ for (i=mi, j=mj; i>=0; i--, j--) {
141+ if (!(i<=0 || j<=0) && lcs[ i] [ j ] != 0) {
142+ ans += s1[ i-1] ;
143+ } else {
144+ break;
145+ }
146+ }
147+ reverse(ans.begin(), ans.end());
148+ cout << "len : " << ma << " is " << ans;
149+ }
150+ ```
You can’t perform that action at this time.
0 commit comments