Skip to content

Commit 7a12921

Browse files
committed
LCSubstring solution added
1 parent ac812fc commit 7a12921

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/* Dynamic Programming solution to find length of the longest common substring*/
2+
#include <bits/stdc++.h>
3+
4+
using namespace std;
5+
6+
int LongestCommonSubStr(string X, string Y, int m, int n) {
7+
8+
int dp[m + 1][n + 1];
9+
int result = 0;
10+
11+
for (int i = 0; i <= m; i++) {
12+
for (int j = 0; j <= n; j++) {
13+
if (i == 0 || j == 0)
14+
dp[i][j] = 0;
15+
16+
else if (X[i - 1] == Y[j - 1]) {
17+
dp[i][j] = dp[i - 1][j - 1] + 1;
18+
result = max(result, dp[i][j]);
19+
} else
20+
dp[i][j] = 0;
21+
}
22+
}
23+
return result;
24+
}
25+
26+
int main() {
27+
string X = "FirstCommit";
28+
string Y = "LastCommit";
29+
30+
int m = X.length();
31+
int n = Y.length();
32+
33+
cout << "Length of Longest Common Substring is " << LongestCommonSubStr(X, Y, m, n);
34+
return 0;
35+
}

0 commit comments

Comments
 (0)