一个字符串采用string对象存储,设计一个算法判断该字符串是否为回文。

一个字符串采用string对象存储,设计一个算法判断该字符串是否为回文。
求解思路:首先我们要知道回文是正着念和倒着念一样的,定义一个string类型的字符串,然后让他首(递增)尾(递减)比较,如果不相等就返回错误,否则返回正确。

include

include

using namespace std;
bool solve(string str)
{
int i=0;
int j=str.length()-1;
while(i<j)
{
if(str[i]!=str[j])
return false;
i++;j–;
}
return true;
}
int main()
{
cout <<“求解结果”<< endl;
string str=“abba”;
cout <<" "<<str<<(solve(str)?“是回文”:“不是回文”)<<endl;
return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42160112/article/details/100918368