Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
longest_palindromic_subsequence.cpp File Reference

Program to find the Longest Palindormic Subsequence of a string. More...

#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
Include dependency graph for longest_palindromic_subsequence.cpp:

Functions

std::string lps (std::string a)
 
void test ()
 
int main ()
 

Detailed Description

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

Function Documentation

◆ lps()

Function that returns the longest palindromic subsequence of a string

25 {
26 std::string b = a;
27 reverse(b.begin(), b.end());
28 int m = a.length();
30
31 // Finding the length of the longest
32 // palindromic subsequence and storing
33 // in a 2D array in bottoms-up manner
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 // Length of longest palindromic subsequence
46 int idx = res[m][m];
47 // Creating string of index+1 length
48 std::string ans(idx + 1, '\0');
49 int i = m, j = m;
50
51 // starting from right-most bottom-most corner
52 // and storing them one by one in ans
53 while (i > 0 && j > 0) {
54 // if current characters in a and b are same
55 // then it is a part of the ans
56 if (a[i - 1] == b[j - 1]) {
57 ans[idx - 1] = a[i - 1];
58 i--;
59 j--;
60 idx--;
61 }
62 // If they are not same, find the larger of the
63 // two and move in that direction
64 else if (res[i - 1][j] > res[i][j - 1]) {
65 i--;
66 } else {
67 j--;
68 }
69 }
70
71 return ans;
72}
T begin(T... args)
T end(T... args)
ll ans(ll n)
Definition: matrix_exponentiation.cpp:91
T max(T... args)
T reverse(T... args)
Here is the call graph for this function:

◆ main()

int main ( void  )

Main Function

87 {
88 test(); // execute the tests
89 return 0;
90}
void test()
Definition: longest_palindromic_subsequence.cpp:75
Here is the call graph for this function:

◆ test()

void test ( )

Test function

75 {
76 // lps("radar") return "radar"
77 assert(lps("radar") == "radar");
78 // lps("abbcbaa") return "abcba"
79 assert(lps("abbcbaa") == "abcba");
80 // lps("bbbab") return "bbbb"
81 assert(lps("bbbab") == "bbbb");
82}
std::string lps(std::string a)
Definition: longest_palindromic_subsequence.cpp:25
Here is the call graph for this function: