Merge branch 'master' into longest_common_string_patch

This commit is contained in:
realstealthninja
2023-06-01 06:32:07 +05:30
committed by GitHub
6 changed files with 205 additions and 82 deletions

View File

@@ -1,7 +1,7 @@
/**
* @file
* @brief Program to find the Longest Palindormic
* Subsequence of a string
* @brief Program to find the [Longest Palindormic
* Subsequence](https://www.geeksforgeeks.org/longest-palindromic-subsequence-dp-12/) of a string
*
* @details
* [Palindrome](https://en.wikipedia.org/wiki/Palindrome) string sequence of
@@ -13,26 +13,33 @@
* @author [Anjali Jha](https://github.com/anjali1903)
*/
#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
#include <cassert> /// for assert
#include <string> /// for std::string
#include <vector> /// for std::vector
/**
* Function that returns the longest palindromic
* subsequence of a string
* @namespace
* @brief Dynamic Programming algorithms
*/
std::string lps(std::string a) {
std::string b = a;
reverse(b.begin(), b.end());
int m = a.length();
std::vector<std::vector<int> > res(m + 1);
namespace dynamic_programming {
/**
* @brief Function that returns the longest palindromic
* subsequence of a string
* @param a string whose longest palindromic subsequence is to be found
* @returns longest palindromic subsequence of the string
*/
std::string lps(const std::string& a) {
const auto b = std::string(a.rbegin(), a.rend());
const auto m = a.length();
using ind_type = std::string::size_type;
std::vector<std::vector<ind_type> > res(m + 1,
std::vector<ind_type>(m + 1));
// Finding the length of the longest
// palindromic subsequence and storing
// in a 2D array in bottoms-up manner
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= m; j++) {
for (ind_type i = 0; i <= m; i++) {
for (ind_type j = 0; j <= m; j++) {
if (i == 0 || j == 0) {
res[i][j] = 0;
} else if (a[i - 1] == b[j - 1]) {
@@ -43,10 +50,10 @@ std::string lps(std::string a) {
}
}
// Length of longest palindromic subsequence
int idx = res[m][m];
auto idx = res[m][m];
// Creating string of index+1 length
std::string ans(idx + 1, '\0');
int i = m, j = m;
std::string ans(idx, '\0');
ind_type i = m, j = m;
// starting from right-most bottom-most corner
// and storing them one by one in ans
@@ -70,19 +77,22 @@ std::string lps(std::string a) {
return ans;
}
} // namespace dynamic_programming
/** Test function */
void test() {
// lps("radar") return "radar"
assert(lps("radar") == "radar");
// lps("abbcbaa") return "abcba"
assert(lps("abbcbaa") == "abcba");
// lps("bbbab") return "bbbb"
assert(lps("bbbab") == "bbbb");
/**
* @brief Self-test implementations
* @returns void
*/
static void test() {
assert(dynamic_programming::lps("radar") == "radar");
assert(dynamic_programming::lps("abbcbaa") == "abcba");
assert(dynamic_programming::lps("bbbab") == "bbbb");
assert(dynamic_programming::lps("") == "");
}
/**
* Main Function
* @brief Main Function
* @returns 0 on exit
*/
int main() {
test(); // execute the tests