From 4fc14710b60c265f265bd4d7c526207a5d477421 Mon Sep 17 00:00:00 2001 From: Piotr Idzik <65706193+vil02@users.noreply.github.com> Date: Thu, 18 May 2023 19:26:06 +0200 Subject: [PATCH] fix: segv in `longest_palindromic_subsequence.cpp` (#2461) * fix: initialise properly res, set properly size of ans * test: add check with empty input * style: use const reference as input type * refactor: add ind_type * style: use reverse interators to b * style: use auto in definition of idx * updating DIRECTORY.md * style: clean-up includes * style: use std::string::size_type in definition of ind_type --------- Co-authored-by: github-actions[bot] Co-authored-by: David Leal --- .../longest_palindromic_subsequence.cpp | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/dynamic_programming/longest_palindromic_subsequence.cpp b/dynamic_programming/longest_palindromic_subsequence.cpp index 9505dcc10..870c43b9c 100644 --- a/dynamic_programming/longest_palindromic_subsequence.cpp +++ b/dynamic_programming/longest_palindromic_subsequence.cpp @@ -13,26 +13,26 @@ * @author [Anjali Jha](https://github.com/anjali1903) */ -#include -#include -#include -#include +#include /// for assert +#include /// for std::string +#include /// for std::vector /** * Function that returns the longest palindromic * subsequence of a string */ -std::string lps(std::string a) { - std::string b = a; - reverse(b.begin(), b.end()); - int m = a.length(); - std::vector > res(m + 1); +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 > res(m + 1, + std::vector(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 +43,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 @@ -73,12 +73,10 @@ std::string lps(std::string a) { /** 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"); + assert(lps("") == ""); } /**