Skip to content

Commit

Permalink
added code 11 (#121)
Browse files Browse the repository at this point in the history
  • Loading branch information
divyakhetan authored and MadhavBahl committed Jan 3, 2019
1 parent 8163e59 commit 01da629
Show file tree
Hide file tree
Showing 2 changed files with 112 additions and 0 deletions.
52 changes: 52 additions & 0 deletions day11/C++/longestCommonSubstringday11.cpp
@@ -0,0 +1,52 @@
/**
* @author:divyakhetan
* @date: 3/1/2019
*/



#include <bits/stdc++.h>
using namespace std;

int main() {
string s1,s2;
cin >> s1 >> s2;

int n = s1.length();
int m = s2.length();

int lcs[n + 1][m + 1];

int ma = 0;
int mi = 0;
int mj = 0;
for(int i =0; i <=n; i++){
for(int j = 0; j <=m;j++){
if(i == 0 || j == 0) lcs[i][j] = 0;
else if(s1[i -1] == s2[j - 1]){
lcs[i][j] = 1 + lcs[i - 1][j - 1];
if(lcs[i][j] > ma){
mi = i;
mj = j;
ma = lcs[i][j];
}

}
else{
lcs[i][j]= 0;
}
}
}
int i = 0;
int j = 0;
string ans= "";
for (i=mi, j=mj; i>=0; i--, j--) {
if (!(i<=0 || j<=0) && lcs[i][j] != 0) {
ans += s1[i-1];
} else {
break;
}
}
reverse(ans.begin(), ans.end());
cout << "len : " << ma << " is " << ans;
}
60 changes: 60 additions & 0 deletions day11/README.md
Expand Up @@ -88,3 +88,63 @@ function longestSubstring (str1, str2) {
console.log(longestSubstring ("abcdefg", "xyabcz"));
console.log(longestSubstring ("XYXYXYZ", "XYZYX"));
```


## C++ Implementation

### [Solution using dynamic programming](./C++/longestCommonSubstringday11.cpp)

```cpp
/**
* @author:divyakhetan
* @date: 3/1/2019
*/



#include <bits/stdc++.h>
using namespace std;

int main() {
string s1,s2;
cin >> s1 >> s2;

int n = s1.length();
int m = s2.length();

int lcs[n + 1][m + 1];

int ma = 0;
int mi = 0;
int mj = 0;
for(int i =0; i <=n; i++){
for(int j = 0; j <=m;j++){
if(i == 0 || j == 0) lcs[i][j] = 0;
else if(s1[i -1] == s2[j - 1]){
lcs[i][j] = 1 + lcs[i - 1][j - 1];
if(lcs[i][j] > ma){
mi = i;
mj = j;
ma = lcs[i][j];
}

}
else{
lcs[i][j]= 0;
}
}
}
int i = 0;
int j = 0;
string ans= "";
for (i=mi, j=mj; i>=0; i--, j--) {
if (!(i<=0 || j<=0) && lcs[i][j] != 0) {
ans += s1[i-1];
} else {
break;
}
}
reverse(ans.begin(), ans.end());
cout << "len : " << ma << " is " << ans;
}
```

0 comments on commit 01da629

Please sign in to comment.