我正在尝试为回文写一个递归函数。当我在没有输入命令参数的情况下测试字符串时,我得到了正确的答案。当有命令参数时。即使认为它是真的,它也会不断返回错误。我做错了什么。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
bool palindrome(string word);
string formatString(string s);
int main(int argc , char * argv[])
{
if(argc < 2)
{
string inputString;
int last = inputString.length()-1;
cout << "Welcome To My Palidrome Tester!" << endl;
cout << "Please Enter A String To Test if it is A Palidrome: ";
getline(cin, inputString);
//testForPalindrome(inputString);
string newW = formatString(inputString);
//cout << "It is a palindrome" ? (palindrome(newW) == true) : "It is Not a palidrome";
if(palindrome(newW) == true)
cout << "It is a palindrome" << endl;
else
cout << "It is not palindrome" << endl;
}
else
{
string commandStr;
for(int i = 1; i < argc; i++)
{
commandStr += argv[i];
}
string newW = formatString(commandStr);
if(palindrome(newW) == true)
cout << "It is a palindrome" << endl;
else
cout << "It is not 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));
if (word.length() <= 1) return true; // Problem line?
palindrome(word);
}
else
return false;
}
string formatString(string s)
{
string p;
size_t position = s.find(' ', 0);
while(position != string::npos)
{
s.erase(position,1);
size_t newPosition = position+1;
position = s.find(' ', newPosition);
}
for(int i = 0; i < s.size(); i++)
{
if(ispunct(s[i]))
{
s.erase(i,1);
}
if(isupper(s[i]))
{
s = tolower(s[i]);
}
}
return s;
}
最佳答案
string inputString;
int last = inputString.length()-1;
您过早地获取了字符串的长度。改为
string inputString;
cout << "Please Enter A String To Test if it is A Palidrome: ";
getline(cin, inputString);
formatString(inputString);
int last = inputString.length() - 1;
if (recursionPalindrome(inputString, 0, last) != 0)
cout << "It is a Palindrome" << endl;
else
cout << "It is not a palindrome" << endl;
关于c++ - 递归回文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40068788/