Program to find the Longest Palindormic Subsequence of a string.
More...
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
Program to find the Longest Palindormic Subsequence of a string.
Palindrome string sequence of characters which reads the same backward as forward Subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
- Author
- Anjali Jha
◆ lps()
Function that returns the longest palindromic subsequence of a string
25 {
28 int m = a.length();
30
31
32
33
34 for (int i = 0; i <= m; i++) {
35 for (int j = 0; j <= m; j++) {
36 if (i == 0 || j == 0) {
37 res[i][j] = 0;
38 } else if (a[i - 1] == b[j - 1]) {
39 res[i][j] = res[i - 1][j - 1] + 1;
40 } else {
41 res[i][j] =
std::max(res[i - 1][j], res[i][j - 1]);
42 }
43 }
44 }
45
46 int idx = res[m][m];
47
49 int i = m, j = m;
50
51
52
53 while (i > 0 && j > 0) {
54
55
56 if (a[i - 1] == b[j - 1]) {
57 ans[idx - 1] = a[i - 1];
58 i--;
59 j--;
60 idx--;
61 }
62
63
64 else if (res[i - 1][j] > res[i][j - 1]) {
65 i--;
66 } else {
67 j--;
68 }
69 }
70
72}
ll ans(ll n)
Definition: matrix_exponentiation.cpp:91
◆ main()
Main Function
87 {
89 return 0;
90}
void test()
Definition: longest_palindromic_subsequence.cpp:75
◆ test()
Test function
75 {
76
77 assert(
lps(
"radar") ==
"radar");
78
79 assert(
lps(
"abbcbaa") ==
"abcba");
80
81 assert(
lps(
"bbbab") ==
"bbbb");
82}
std::string lps(std::string a)
Definition: longest_palindromic_subsequence.cpp:25