TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
longest_palindromic_subsequence.cpp
Go to the documentation of this file.
1
15
16
#include <cassert>
17
#include <string>
18
#include <vector>
19
24
namespace
dynamic_programming
{
31
std::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
86
static
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
97
int
main
() {
98
test
();
// execute the tests
99
return
0;
100
}
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
dynamic_programming
Dynamic Programming algorithms.
dynamic_programming::lps
std::string lps(const std::string &a)
Function that returns the longest palindromic subsequence of a string.
Definition
longest_palindromic_subsequence.cpp:31
dynamic_programming
longest_palindromic_subsequence.cpp
Generated by
1.18.0