TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
longest_palindromic_subsequence.cpp
Go to the documentation of this file.
1
16#include <cassert>
17#include <string>
18#include <vector>
19
24namespace dynamic_programming {
31std::string lps(const std::string& a) {
32 const auto b = std::string(a.rbegin(), a.rend());
33 const auto m = a.length();
34 using ind_type = std::string::size_type;
35 std::vector<std::vector<ind_type> > res(m + 1,
36 std::vector<ind_type>(m + 1));
37
38 // Finding the length of the longest
39 // palindromic subsequence and storing
40 // in a 2D array in bottoms-up manner
41 for (ind_type i = 0; i <= m; i++) {
42 for (ind_type j = 0; j <= m; j++) {
43 if (i == 0 || j == 0) {
44 res[i][j] = 0;
45 } else if (a[i - 1] == b[j - 1]) {
46 res[i][j] = res[i - 1][j - 1] + 1;
47 } else {
48 res[i][j] = std::max(res[i - 1][j], res[i][j - 1]);
49 }
50 }
51 }
52 // Length of longest palindromic subsequence
53 auto idx = res[m][m];
54 // Creating string of index+1 length
55 std::string ans(idx, '\0');
56 ind_type i = m, j = m;
57
58 // starting from right-most bottom-most corner
59 // and storing them one by one in ans
60 while (i > 0 && j > 0) {
61 // if current characters in a and b are same
62 // then it is a part of the ans
63 if (a[i - 1] == b[j - 1]) {
64 ans[idx - 1] = a[i - 1];
65 i--;
66 j--;
67 idx--;
68 }
69 // If they are not same, find the larger of the
70 // two and move in that direction
71 else if (res[i - 1][j] > res[i][j - 1]) {
72 i--;
73 } else {
74 j--;
75 }
76 }
77
78 return ans;
79}
80} // namespace dynamic_programming
81
86static void test() {
87 assert(dynamic_programming::lps("radar") == "radar");
88 assert(dynamic_programming::lps("abbcbaa") == "abcba");
89 assert(dynamic_programming::lps("bbbab") == "bbbb");
90 assert(dynamic_programming::lps("") == "");
91}
92
97int main() {
98 test(); // execute the tests
99 return 0;
100}
static void test()
Self-test implementations.
int main()
Main Function.
Dynamic Programming algorithms.
std::string lps(const std::string &a)
Function that returns the longest palindromic subsequence of a string.