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 +#include +#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
+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.
+For every other entry:
+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].
+Else mat[i][j] = max(mat[i][j-1], mat[i+1][j]).