64,646
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
/*
2013-9-5
编写一个方法用于验证指定的字符串是否为反转字符,返回true和false。请用递归算法实现。
两种情况,字符为奇数,最后剩下中间字符;
字符为偶数,最后没有字符
如:"aba","abba"
*/
bool is_PalindromicStr(string::iterator * p_start, string::iterator* p_end)
{
if (p_start == p_end)
return true;
else if (p_end == (p_start + 1))
return true;
else if (*p_start == *p_end)
is_PalindromicStr(p_start + 1, p_end - 1);
else
return false;
}
int main()
{
string str = "abba";
cout << is_PalindromicStr(str.begin(), str.end()-1) << endl;
return 0;
}
bool is_PalindromicStr(string::iterator p_start, string::iterator p_end)
{
bool ret = false;
//printf("%c %c\n",*p_start, *p_end);
//printf( "%d %d\n",&(*(p_start + 1)), &(*(p_end - 1)) );
if (*p_start == *p_end)
{
ret = true;
if(p_start + 1 <= p_end - 1 )
{
if ( false == is_PalindromicStr(p_start + 1, p_end - 1) )
ret = false;
else
ret = true;
}
}
else
{
//printf("in else\n");
ret = false;
}
return ret;
}
int _tmain(int argc, _TCHAR* argv[])
{
//Object* p = Object::CreateObject("A");
//delete p;
string str = "abdggdba";
cout << is_PalindromicStr(str.begin(), (str.end()-1)) << endl;
system("pause");
return 0;
}
vs2010编译通过。#include <iostream>
#include <stdio.h>
#include <cstring>
using namespace std;
/*
2013-9-5
编写一个方法用于验证指定的字符串是否为反转字符,返回true和false。请用递归算法实现。
两种情况,字符为奇数,最后剩下中间字符;
字符为偶数,最后没有字符
如:"aba","abba"
*/
bool is_PalindromicStr(string::iterator& p_start, string::iterator& p_end) //改动
{
if (p_start == p_end)
return true;
else if (p_end == (p_start - 1)) //改动
return true;
else if (*p_start == *p_end)
return is_PalindromicStr(p_start + 1, p_end - 1); //改动
else
return false;
}
int main()
{
string str = "abba";
cout << is_PalindromicStr(str.begin(), str.end()-1) << endl;
return 0;
}