diff --git a/Competitive Coding/Dynamic Programming/Longest Palindromic Sub-sequence/lps.c b/Competitive Coding/Dynamic Programming/Longest Palindromic Sub-sequence/lps.c new file mode 100644 index 000000000..f2262efb0 --- /dev/null +++ b/Competitive Coding/Dynamic Programming/Longest Palindromic Sub-sequence/lps.c @@ -0,0 +1,48 @@ +#include<stdio.h> +#include<string.h> +#define MAXLEN 100 +// A utility function to get max of two integers +int max (int x, int y) { return (x > y)? x : y; } + +// Returns the length of the longest palindromic subsequence in seq +int lps(char *str) +{ + int n = strlen(str); + int i, j, len; + int mat[n][n]; // Create a table to store results of subproblems + + + // Strings of length 1 are palindrome of lentgh 1 + for (i = 0; i < n; i++) + mat[i][i] = 1; + + /* Build the table. Note that the lower diagonal values of table are + useless and not filled in the process. len is length of + substring*/ + for (len=2; len<=n; len++) + { + for (i=0; i<n-len+1; i++) + { + j = i+len-1; + if (str[i] == str[j] && len == 2) + mat[i][j] = 2; + else if (str[i] == str[j]) + mat[i][j] = mat[i+1][j-1] + 2; + else + mat[i][j] = max(mat[i][j-1], mat[i+1][j]); + } + } + + return mat[0][n-1]; +} + +/* main */ +int main() +{ + printf("Enter your string\n"); + char str[MAXLEN]; + scanf("%99s",str); + printf ("The lnegth of the Longest Palindromic Sub-sequence is %d", lps(str)); + getchar(); + return 0; +} diff --git a/Competitive Coding/Dynamic Programming/Longest Palindromic Sub-sequence/readme_lps.md b/Competitive Coding/Dynamic Programming/Longest Palindromic Sub-sequence/readme_lps.md new file mode 100644 index 000000000..2534f1124 --- /dev/null +++ b/Competitive Coding/Dynamic Programming/Longest Palindromic Sub-sequence/readme_lps.md @@ -0,0 +1,13 @@ +## Longest Common Subsequence + In order to solve this problem using Dynamic Programming, we create a 2-D matrix called mat[n][n], where 'n' is the length of the given string. +Any entry [i][j] in the matrix represents the length of the longest palindromic sub-sequence from 'i'th charecter of the string to the 'j'th. +As the string is always considereed from left to right i<=j always. Hence the lower triangle of the matrix is of no use. + +### Filling of the matrix + Every single charecter contributes to a palindromic string of length 1 starting and ending at itself, therefore we fill the diagonal of the +matrix with 1 for every [i][i] entry. <br/><br/> +Let str[0..n-1] be the input sequence of length n, then mat[0][n-1] will be the length of the longest palindromic subsequence.<br/> +For every other entry:<br/> +If last and first characters of str are same, then mat[i][j] = mat[i+1][j-1] + 2, as it considers [2(for the first and the last chaar)] + +[longest palindromic subsequence between these 2 chars].<br/> +Else mat[i][j] = max(mat[i][j-1], mat[i+1][j]).