回文递归版本

Palindrome recursive version

本文关键字:版本 递归 回文      更新时间:2023-10-16

我写了一个递归函数来查找一个单词是否是回文,但我不明白为什么函数在递归结束时返回一个 TRUE 值,而在此之前它打印 FALSE。

这是我的代码:

#include <iostream>
#include <string>
using namespace std;
bool palindrome_recursive(string word){
string::size_type wordLength = word.length();
if(wordLength == 0){
cout << "TRUE" <<endl;
return true;
}
if(word.at(0) != word.at(wordLength-1)){
cout << "FALSE" <<endl;
return false;
}
word.erase(wordLength-1);
word.erase(0,1);
cout << word << endl;
palindrome_recursive(word);
return true;
}

int main()
{
std::cout << "Enter a word: ";
std::string word;
std::cin >> word;
if(palindrome_recursive(word)){
std::cout << word << " is a palindrome" << std::endl;
} else {
std::cout << word << " is not a palindrome" << std::endl;
}
}  

因为你返回true,而不是递归调用的结果。将其更改为:

return palindrome_recursive(word);

在这里,无论palindrome_recursive返回什么,您都会返回true

palindrome_recursive(word);
return true;

将其更改为:

return palindrome_recursive(word);