我正在尝试编写一个递归函数来确定字符串是否为回文。这是我目前所拥有的:
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/