Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

c++ - Palindrome testing function with only the string as input

I am trying to write a recursive function in C++ to check if a string is a palindrome or not. (A palindrome is a string that's spelled the same way forward and backward like "radar")

The function must be boolean and only take the string as input.

But it is only working for strings with two letters. Anything more than that and it always returns 1.

Here is the code:

bool testPalindrome (string x) {
  static int y = 1;
  static int z = x.size();
  if ((z - y == 1 || z - y == 2) && x[x.size() - z] == x[x.size() - y]) {
    return true;
  } else if (x[x.size() - z] == x[x.size() - y]) {
    --z;
    ++y;
    testPalindrome(x);
  } else {
    return false;
  }
}
question from:https://stackoverflow.com/questions/65851294/palindrome-testing-function-with-only-the-string-as-input

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you are using recursion, one key thing to note is you have to return the output produced by the recursive function. In this case, you need a return statement in the second if.

Here is the working code:

bool testPalindrome (string x){
static int y = 1;
static int z = x.length();
    if( (z-y == 1||z-y == 2) && x[x.length() - z] == x[x.length() - y]){
        return true;
    }
    else if(x[x.length() - z] == x[x.length() - y]){
        --z;
        ++y;
        return testPalindrome(x);
    }
    else{
        return false;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...