-1

I am a beginner in C++, so it may be a stupid mistake. So, I wrote the following code to find longest palindrome in any word:

#include<bits/stdc++.h>
#include<string>
using namespace std;

bool IsPal(string str)
{ 
  int length = str.length();
  if (length < 1) return true;
  else if (str.at(0) == str.at(length-1)) {str = str.substr(1, (length-2)); return IsPal(str);}
  else return false;
}

int main()
{
  int n;
  cin >> n;

  string x;
  int *arRes = new int[n];

  for (int i = 0; i < n; i++)
  {
    unsigned int maxim = 1;
    cin >> x;

    for (int j = 0; j < n; j++)
    {
      string sub = x.substr(0, j);

      if(IsPal(sub))
      {
        if(sub.length() > maxim)
        { maxim = sub.length(); }
      }
    }
    
    arRes[i] = maxim;  
  }
  for (int i = 0; i < n; i++)
  {
    cout << arRes[i] << endl; 
  }
  delete [] arRes;
}

And it doesn't pass this test:

8
woweffect
abccbaabc
testme
strstr
ababab
abcdefg
tetatet
aaaaaaaaaaaaa

It prints 3 6 1 1 5 1 7 7 instead of 3 6 1 1 5 1 7 13 and I can't understand why. Can someone explain it?

  • So `aaaaaaaaaaaaa` is the only case it fails on? Why don't you debug only that? Or perhaps maybe `aaa` – drescherjm Nov 30 '20 at 16:43
  • Related: https://stackoverflow.com/q/1115001/10553341 – Damien Nov 30 '20 at 17:02
  • O.T.: Considering that you only read the input string, all these copies with new `string`s appear as performance overkill to me. You may use [std::string_view](https://en.cppreference.com/w/cpp/string/basic_string_view) instead from which you can get parts of the string with `std::string_view::substr()` without copying anything. – Scheff's Cat Nov 30 '20 at 17:09

1 Answers1

2

Here

for (int j = 0; j < n; j++)
    {
      string sub = x.substr(0, j);

You are taking substrings of the input strings starting from the first character till the j-th and j goes from 0 till n.

However, n is the number of test cases, wich is 8 in your example (output is 7 because of j < n). You probably want j to loop from 0 till x.size() instead.

Using variable names that actually give meaningful names to variables helps to avoid this and countless other problems. For example number_of_test_cases instead of n. Then read the same code again:

for (int sub_string_size = 0; sub_string_size < number_of_test_cases; sub_string_size++)
    {
      string sub = x.substr(0, sub_string_size);
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185