File tree 1 file changed +44
-0
lines changed
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
1
+ // A Dynamic Programming based C++ program for LPS problem
2
+ // Returns the length of the longest palindromic subsequence in seq
3
+ #include < stdio.h>
4
+ #include < string.h>
5
+
6
+ int max (int x, int y) { return (x > y)? x : y; }
7
+
8
+ int lps (char *str)
9
+ {
10
+ int n = strlen (str);
11
+ int i, j, cl;
12
+ int L[n][n];
13
+
14
+
15
+ // Strings of length 1 are palindrome of length 1
16
+ for (i = 0 ; i < n; i++)
17
+ L[i][i] = 1 ;
18
+
19
+ for (cl=2 ; cl<=n; cl++)
20
+ {
21
+ for (i=0 ; i<n-cl+1 ; i++)
22
+ {
23
+ j = i+cl-1 ;
24
+ if (str[i] == str[j] && cl == 2 )
25
+ L[i][j] = 2 ;
26
+ else if (str[i] == str[j])
27
+ L[i][j] = L[i+1 ][j-1 ] + 2 ;
28
+ else
29
+ L[i][j] = max (L[i][j-1 ], L[i+1 ][j]);
30
+ }
31
+ }
32
+
33
+ return L[0 ][n-1 ];
34
+ }
35
+
36
+ /* Driver program to test above functions */
37
+ int main ()
38
+ {
39
+ char seq[] = " GEEKS FOR GEEKS" ;
40
+ int n = strlen (seq);
41
+ printf (" The length of the LPS is %d" , lps (seq));
42
+ getchar ();
43
+ return 0 ;
44
+ }
You can’t perform that action at this time.
0 commit comments