Program to find the Longest Palindormic Subsequence of a string.
More...
#include <cassert>
#include <string>
#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()
for assert for std::string for std::vector Function that returns the longest palindromic subsequence of a string
24 {
26 const auto m = a.length();
27 using ind_type = std::string::size_type;
30
31
32
33
34 for (ind_type i = 0; i <= m; i++) {
35 for (ind_type 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 auto idx = res[m][m];
47
49 ind_type 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
71 return ans;
72}
◆ main()
Main Function
85 {
87 return 0;
88}
void test()
Definition: longest_palindromic_subsequence.cpp:75
◆ test()
Test function
75 {
76 assert(
lps(
"radar") ==
"radar");
77 assert(
lps(
"abbcbaa") ==
"abcba");
78 assert(
lps(
"bbbab") ==
"bbbb");
79 assert(
lps(
"") ==
"");
80}
std::string lps(const std::string &a)
Definition: longest_palindromic_subsequence.cpp:24