【问题标题】:Palindrome Recursion Not Stopping回文递归没有停止
【发布时间】:2019-11-23 15:40:56
【问题描述】:

我已经构建了框架,但是遇到了一个我无法捕捉到的逻辑错误。为了总结它的作用,它将一个字符串传递给 book 函数并检查第一个和最后一个字符,如果有相同的继续这样做,直到剩下一个字符。如果字母不相同,则返回 false。但是,当输入有效的回文时,结果会出现错误,它会到达基本情况,但不会停止递归并最终返回 0,而实际上它是回文。任何关于它为什么没有停止的见解都会很棒!

#include <iostream>
#include <string>
#include <cctype>
#include <cstring>
#include <cstdio>
using namespace std;

bool book(string origWord, int len);



int main()
{
    string a = "ABCDCBA";
    cout << "Test:" << book(a, a.length() - 1);
    return 0;
}
bool book(string origWord, int len)
{
    bool status = false;
    if (len <= 1)
    {
        status = true;
    }
    else if (tolower(origWord[0]) == tolower(origWord[len]))
    {
        book(origWord.substr(1, len - 1), len - 2);
    }

    return status;
}

【问题讨论】:

    标签: c++ recursion palindrome


    【解决方案1】:
    else if (tolower(origWord[0]) == tolower(origWord[len]))
    {
        book(origWord.substr(1, len - 1), len - 2);
    }
    

    在这里,您丢弃从 book 返回的值。你可能想要这个:

    status = book(origWord.substr(1, len - 1), len - 2);
    

    【讨论】:

      【解决方案2】:

      以下是控制流经此函数的方式:

      bool book(string origWord, int len)
      {
          bool status = false;  // 1. status is FALSE
          if (len <= 1)  // 2. This branch is not taken
          {
              status = true;
          }
          else if (tolower(origWord[0]) == tolower(origWord[len]))  // 3. This branch IS taken
          {
              book(origWord.substr(1, len - 1), len - 2);  // 4. Say, this returns TRUE
              // 5. but the return value is not used
          }
          // 6. control passes here after executing the function
          // 7. local status is STILL FALSE
          return status;  // 8. return status, which is FALSE 
      }
      

      如何解决:

      bool book(string origWord, int len)
      {
          if (len <= 1)
          {
              return true;
          }
          else if (tolower(origWord[0]) == tolower(origWord[len]))
          {
              // Use the RETURNED VALUE!
              return book(origWord.substr(1, len - 1), len - 2);
          }
      
          return false;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-03-30
        • 2018-04-24
        • 2013-05-18
        • 1970-01-01
        • 2021-07-20
        • 1970-01-01
        相关资源
        最近更新 更多