Skip to content

Commit 4fc1471

Browse files
vil02github-actions[bot]Panquesito7
authored
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] <[email protected]> Co-authored-by: David Leal <[email protected]>
1 parent 6027480 commit 4fc1471

File tree

1 file changed

+15
-17
lines changed

1 file changed

+15
-17
lines changed

dynamic_programming/longest_palindromic_subsequence.cpp

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -13,26 +13,26 @@
1313
* @author [Anjali Jha](https://github.com/anjali1903)
1414
*/
1515

16-
#include <algorithm>
17-
#include <cassert>
18-
#include <iostream>
19-
#include <vector>
16+
#include <cassert> /// for assert
17+
#include <string> /// for std::string
18+
#include <vector> /// for std::vector
2019

2120
/**
2221
* Function that returns the longest palindromic
2322
* subsequence of a string
2423
*/
25-
std::string lps(std::string a) {
26-
std::string b = a;
27-
reverse(b.begin(), b.end());
28-
int m = a.length();
29-
std::vector<std::vector<int> > res(m + 1);
24+
std::string lps(const std::string& a) {
25+
const auto b = std::string(a.rbegin(), a.rend());
26+
const auto m = a.length();
27+
using ind_type = std::string::size_type;
28+
std::vector<std::vector<ind_type> > res(m + 1,
29+
std::vector<ind_type>(m + 1));
3030

3131
// Finding the length of the longest
3232
// palindromic subsequence and storing
3333
// in a 2D array in bottoms-up manner
34-
for (int i = 0; i <= m; i++) {
35-
for (int j = 0; j <= m; j++) {
34+
for (ind_type i = 0; i <= m; i++) {
35+
for (ind_type j = 0; j <= m; j++) {
3636
if (i == 0 || j == 0) {
3737
res[i][j] = 0;
3838
} else if (a[i - 1] == b[j - 1]) {
@@ -43,10 +43,10 @@ std::string lps(std::string a) {
4343
}
4444
}
4545
// Length of longest palindromic subsequence
46-
int idx = res[m][m];
46+
auto idx = res[m][m];
4747
// Creating string of index+1 length
48-
std::string ans(idx + 1, '\0');
49-
int i = m, j = m;
48+
std::string ans(idx, '\0');
49+
ind_type i = m, j = m;
5050

5151
// starting from right-most bottom-most corner
5252
// and storing them one by one in ans
@@ -73,12 +73,10 @@ std::string lps(std::string a) {
7373

7474
/** Test function */
7575
void test() {
76-
// lps("radar") return "radar"
7776
assert(lps("radar") == "radar");
78-
// lps("abbcbaa") return "abcba"
7977
assert(lps("abbcbaa") == "abcba");
80-
// lps("bbbab") return "bbbb"
8178
assert(lps("bbbab") == "bbbb");
79+
assert(lps("") == "");
8280
}
8381

8482
/**

0 commit comments

Comments
 (0)