Search code examples
c++stringfor-loopmaxpalindrome

Problem with IF condition and && OPERATOR


i have encountered a major problem in my code that, when i hits 1 and j is 5, although, the boolean function returns False, the IF statement still manage to operate.

#include <iostream>
using namespace std;
#include <string>

using namespace std;

bool checkSym(string s, int left, int right) {
  if (left >= right)
    return true;
  else {
    if (int(s[left]) != int(s[right]))
      return false;
    else {
      checkSym(s, left + 1, right - 1);
    }
  }
}
int main() {
  // TODO
  string s, c, d;
  s = "babadad";
  int max = 0;
  int n = s.length();
  for (int i = 0; n - i >= max; i++) {
    c = "";
    for (int j = max; j <= n - i; j++) {
      c = s.substr(i, j);
      if (checkSym(c, 0, j - 1) && j > max) {
        max = j;
        d = c;
      }
    }
  }
  cout << d;
}

Solution

  • The code looks unreadable. Nevertheless at least this function

    bool checkSym(string s, int left, int right) {
      if (left >= right)
        return true;
      else {
        if (int(s[left]) != int(s[right]))
          return false;
        else {
          checkSym(s, left + 1, right - 1);
        }
      }
    }
    

    can invoke undefined behavior because it returns nothing in this code snippet

        else {
          checkSym(s, left + 1, right - 1);
        }
    

    You need to write

        else {
          return checkSym(s, left + 1, right - 1);
        }
    

    Also it is unclear why there is used explicit casting to the type int

     if (int(s[left]) != int(s[right]))
    

    instead of just writing

     if ( s[left] != s[right])