Problem 04. 回文串问题
题目简述:
请写一个程序判断读入的字符串是否是“回文”,如果一个字符串是回文串,则输出"yes",否则输出"no"。
解题思路:
将一个字符串的所有字符放入一个数组,然后依次比较两头的字符是否一样,并记录字符一样的次数c,然后通过c来判断是否回文。
细节处理:for(int i=0,j=m-1;i<j;i++,j--)
{
if(ch[i]==ch[j])
c++;
}
用这个循环可以减少循环的次数,为优化方案。
源代码:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
int n,m,c;
cin>>n;
for(int i=0;i<n;i++)
{
char ch[101];
cin>>ch;
m=strlen(ch);//用来获得输入字符串的长度
c=0;
for(int i=0,j=m-1;i<j;i++,j--)
{
if(ch[i]==ch[j])
c++;
}//比较首尾字符是否一样并用c来计数
if(c==m/2) cout<<"yes"<<endl;
else cout<<"no"<<endl;
}
return 0;
}