Last active
July 1, 2019 17:28
-
-
Save manojnaidu619/271e62b92325ef0381f308cbf6974d2c to your computer and use it in GitHub Desktop.
Finding Longest Common Subsequence in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<string.h> | |
int max(int a, int b); | |
void findLCS(char X[], char Y[], int XLen, int YLen); | |
int max(int a, int b) { | |
return (a > b)? a : b; | |
} | |
void findLCS(char X[], char Y[], int XLen, int YLen) { | |
int L[XLen + 1][YLen + 1]; | |
int r, c, i; | |
/* | |
* find the length of the LCS | |
*/ | |
for(r = 0; r <= XLen; r++) { | |
for(c = 0; c <= YLen; c++) { | |
if(r == 0 || c == 0) { | |
L[r][c] = 0; | |
} | |
else if(X[r - 1] == Y[c - 1]) { | |
L[r][c] = L[r - 1][c - 1] + 1; | |
} | |
else { | |
L[r][c] = max(L[r - 1][c], L[r][c - 1]); | |
} | |
} | |
} | |
/* | |
* Print LCS | |
*/ | |
r = XLen; | |
c = YLen; | |
i = L[r][c]; | |
char LCS[i+1]; // Creating a char type array of size L[r][c]+1 | |
/* | |
* setting the NULL character at the end of LCS character array. | |
* as we know in C programming language, NULL character is used | |
* to denote the end of a string | |
*/ | |
LCS[i] = '\0'; | |
while(r > 0 && c > 0) { | |
if(X[r - 1] == Y[c - 1]) { | |
LCS[i - 1] = X[r - 1]; | |
i--; | |
r--; | |
c--; | |
} | |
else if(L[r - 1][c] > L[r][c - 1]) { | |
r--; | |
} | |
else { | |
c--; | |
} | |
} | |
//print result | |
printf("LCS: %s\n", LCS); | |
printf("Length of the LCS: %d\n", L[XLen][YLen]); | |
} | |
int main(void) { | |
char X[50]; | |
char Y[50]; | |
printf("Enter String 1 : "); | |
scanf("%s",X); | |
printf("Enter String 2 : "); | |
scanf("%s",Y); | |
int XLen = strlen(X); | |
int YLen = strlen(Y); | |
findLCS(X, Y, XLen, YLen); | |
return 0; | |
} | |
// References : https://www.youtube.com/watch?v=cfCdtJSu5pc |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment