仅以字符串作为输入的回文测试函数 我试图在C++中编写递归函数来检查字符串是否是回文。(回文是一个前后拼写相同的字符串,就像“雷达”)

仅以字符串作为输入的回文测试函数 我试图在C++中编写递归函数来检查字符串是否是回文。(回文是一个前后拼写相同的字符串,就像“雷达”),c++,C++,该函数必须是布尔函数,并且只接受字符串作为输入 但它只适用于两个字母的字符串。任何比这更大的值,它总是返回1 代码如下: bool testPalindrome(字符串x){ 静态int y=1; 静态int z=x.size(); 如果((z-y==1 | | z-y==2)和&x[x.size()-z]==x[x.size()-y]){ 返回true; }如果(x[x.size()-z]==x[x.size()-y]){ --z; ++y; 测试回文组(x); }否则{ 返回false; }

该函数必须是布尔函数,并且只接受字符串作为输入

但它只适用于两个字母的字符串。任何比这更大的值,它总是返回1

代码如下:

bool testPalindrome(字符串x){
静态int y=1;
静态int z=x.size();
如果((z-y==1 | | z-y==2)和&x[x.size()-z]==x[x.size()-y]){
返回true;
}如果(x[x.size()-z]==x[x.size()-y]){
--z;
++y;
测试回文组(x);
}否则{
返回false;
}
}

由于您使用的是递归,需要注意的一个关键问题是必须返回递归函数生成的输出。在这种情况下,您需要在第二个if中使用return语句

以下是工作代码:

bool testPalindrome (string x){
static int y = 1;
static int z = x.length();
    if( (z-y == 1||z-y == 2) && x[x.length() - z] == x[x.length() - y]){
        return true;
    }
    else if(x[x.length() - z] == x[x.length() - y]){
        --z;
        ++y;
        return testPalindrome(x);
    }
    else{
        return false;
    }
}

<>这是一个更多的C++ IOP解决方案< /P>
#include <iostream>
#include <string>

using namespace std;

bool testPalindrome(string inString)
{
    if (inString.size() < 2)
        return true;
    else if (inString.front() != inString.back())
        return false;
    else
        return (testPalindrome(inString.substr(1, inString.size() - 2)));
}

int main()
{
    cout << testPalindrome("racecar") << endl;
    cout << testPalindrome("race") << endl;
}
#包括
#包括
使用名称空间std;
布尔测试回文(字符串插入)
{
如果(安装尺寸()<2)
返回true;
else if(inString.front()!=inString.back())
返回false;
其他的
return(testPalindrome(inString.substr(1,inString.size()-2));
}
int main()
{

如果你不使用像
x
y
这样的名称,而是相应地命名变量,那不是很好吗?现在真的很难读取。如果进程流转到中间,你就不会返回任何内容。当你递归调用
testPalindrome(x)时
,它返回的值会发生什么情况?
static
?为什么?你的函数只能工作一次,不要这样做。像地狱一样作弊。让
bool testPalindrome(string x)
调用另一个进行递归的函数,并使用迭代器标记需要处理的区域的开始和结束。至于你的函数(现在已删除)第一个问题,
sizeof(char)
总是
1
std::string
相当于
std::basic_string
,并且
std::basic_string
不知道任何类型的多字节编码