Skip to content

Commit 7c653a3

Browse files
committed
longest-common-subsequence-implementation
1 parent c5c405e commit 7c653a3

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
//Begin
2+
//Take the array of strings as input.
3+
//function matchedPrefixtill(): find the matched prefix between string s1 and s2 :
4+
// n1 = store length of string s1.
5+
//n2 = store length of string s2.
6+
//for i = 0, j = 0 to i <= n1 – 1 && j <= n2 - 1
7+
// if s1[i] != s2[j]
8+
// break
9+
// result.push_back(s1[i])
10+
// return result
11+
//End
12+
//Begin
13+
//function matchedPrefix(): returns the longest matched prefix from the array of strings:
14+
// for int i = 1 to n - 1
15+
// pre = matchedPrefixtill(pre, a[i])
16+
//return pre.
17+
//End
18+
19+
#include<bits/stdc++.h>
20+
using namespace std;
21+
22+
string matchedPrefixtill(string s1, string s2) {
23+
string res;
24+
int n1 = s1.length(); //store length of string s1.
25+
int n2 = s2.length(); //store length of string s2.
26+
for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) {
27+
if (s1[i] != s2[j])
28+
break;
29+
res.push_back(s1[i]);
30+
}
31+
return (res);
32+
}
33+
string matchedPrefix (string a[], int n) {
34+
string pre = a[0];
35+
for (int i = 1; i <= n - 1; i++)
36+
pre = matchedPrefixtill(pre, a[i]);
37+
return (pre);
38+
}
39+
int main() {
40+
string a[] = {"Tutorialspoint", "Tutor", "Tutorials"}; //taking inputs
41+
int n = sizeof(a) / sizeof(a[0]);
42+
string res = matchedPrefix(a, n);
43+
if (res.length())
44+
cout<<"Longest common subsequence is matched - "<<res.c_str();
45+
else
46+
cout<<"No matched prefix";
47+
return (0);
48+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
public class LongestCommonSubsequence {
2+
3+
/* Returns length of LCS for X[0..m-1], Y[0..n-1] */
4+
int lcs(char[] X, char[] Y, int m, int n)
5+
{
6+
int L[][] = new int[m + 1][n + 1];
7+
8+
/* Following steps build L[m+1][n+1] in bottom up fashion. Note
9+
that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
10+
for (int i = 0; i <= m; i++) {
11+
for (int j = 0; j <= n; j++) {
12+
if (i == 0 || j == 0)
13+
L[i][j] = 0;
14+
else if (X[i - 1] == Y[j - 1])
15+
L[i][j] = L[i - 1][j - 1] + 1;
16+
else
17+
L[i][j] = max(L[i - 1][j], L[i][j - 1]);
18+
}
19+
}
20+
return L[m][n];
21+
}
22+
23+
/* Utility function to get max of 2 integers */
24+
int max(int a, int b)
25+
{
26+
return (a > b) ? a : b;
27+
}
28+

0 commit comments

Comments
 (0)