c++ - 使用递归函数查找字符串回文

标签 c++ recursion palindrome

我正在尝试编写一个递归函数来确定字符串是否为回文。这是我目前所拥有的:

int main()
{
    string word = "madam";

    if (palindrome(word) == true)
        cout << "word is a palindrome!" << endl;
    else
        cout << "word is not a palindrome..." << endl;

    return 0;
}

bool palindrome(string word)
{
    int length = word.length();

    string first = word.substr(0,1);
    string last = word.substr((length - 1), 1);

    if (first == last)
    {
        word = word.substr((0 + 1), (length - 2));
        cout << word << " " << word.length() << endl;  // DEBUGGING
        if (word.length() <= 1) return true;  // Problem line?
        palindrome(word);
    }
    else
        return false;
}

出于某种原因,当递归函数变得足够深,并且 word.length() 小于或等于 1 时,它不会返回 true。我似乎无法弄清楚为什么。这是否与递归函数的工作方式有关,或者我在评论 DEBUGGING 之前如何重新调整行中的单词长度?

我在 C++ 方面没有应有的天赋,所以如果我的编程看起来很糟糕,请原谅。

最佳答案

您至少在这里缺少返回语句:

    if (word.length() <= 1) return true;  // Problem line?
    return palindrome(word);    // ###### HERE !
}
else
    return false;

如果长度不是 1,则您递归调用 palindrome 函数,忽略其返回值,然后始终返回 false。通过我的修复,您将在删除第一个和最后一个字母后返回使用 word 调用的回文函数的结果。

关于c++ - 使用递归函数查找字符串回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22890946/

相关文章:

python - return 语句在 python 递归中不返回任何内容

c++ - VideoInfoHeader2结构时抓帧

java - 将返回案例添加到递归函数

c++ - 如何在 CLion 中显示 C++ 的参数名称提示?

java - 递归方法打印帕斯卡三角形上下颠倒和右侧向上(通过 boolean 值)

Java:回文,没有获得最大数

algorithm - 添加最少数量的字符以构成回文

java - 回文java程序的数组索引越界异常

c++ - 获取窗口的背景颜色

c++ - 修改列表后 std::list<T>::end() 的值是否改变?