c++ - 递归回文

标签 c++

我正在尝试为回文写一个递归函数。当我在没有输入命令参数的情况下测试字符串时,我得到了正确的答案。当有命令参数时。即使认为它是真的,它也会不断返回错误。我做错了什么。

#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/

相关文章:

c++ - 将 C++ 代码从 GCC 移植到 MSVC 的良好做法?

c++ - OS X 上 Carbon OpenGL 应用程序的字体

C++ 读取行到类 vector

c++ - Visual C++ CRT调试

c++ - 输入以空格分隔的数字

c++ - 在 CLion 中使用 freeglut 在 OpenGL 中链接错误

c++ - 如何在派生类 C++ 中访问私有(private)成员

c++ - 使 excel 在单个打印作业中打印多个工作表

c++ - 如何找到将元素插入到 std::map 中的位置而不实际插入它

c++ - 我应该使用 CCArray 在 cocos2d-x 中保存自定义 CCNode 吗?