版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ArchyLi/article/details/70176728
回文:把相同的字符串颠倒过来,产生首尾回环,叫做回文。
例如:1234321、1221、1。
注意:单个字符也是回文。
下面给出两个版本的判断字符串是否是回文的方法。
方法一:递归实现判断一个字符串是否是回文。
bool IsPalindereme(char* str, size_t size)
{
if (size <= 1)
return true;
if (str[0] != str[size - 1])
return false;
return IsPalindereme(++str, size - 2);
}
注意:此处是++str而不是str++,因为str++是先传递了str后++,所以实际上传递的是原来的,所以会出错
如果是str++就会出现如下情况:
方法二:非递归实现判断回文字符串。
bool IsPalindereme(char* str, size_t size)
{
int begin = 0;
int end = size - 1;
while (begin < size)
{
if (str[begin] != str[end])
return false;
++begin;
--end;
}
return true;
}
void Funtest()
{
cout << IsPalindereme("1234321", 7) << endl;
cout << IsPalindereme("", 0) << endl;//特殊情况
cout << IsPalindereme("1221", 4) << endl;
cout << IsPalindereme("1", 1) << endl;
cout << IsPalindereme("1231", 4) << endl;
}
int main()
{
Funtest();
system("pause");
return 0;
}
运行成功后结果为: