/*判断一个字符串是否为回文字符串*/
#include<iostream>
#include<cstring>
using namespace std;
int main(){
char a[101],s[101];
int i,len,mid,next,top;
gets(a);//读入一行字符串
len=strlen(a);//求字符串的长度
mid=len/2-1;//求字符串的中点
cout<<endl;
cout<<"字符串a的长度len为"<<len<<endl;
cout<<"字符串a的中点mid为"<<mid<<" 即字符a["<<mid<<"]为"<<a[mid]<<endl;
cout<<endl;
top=0;//栈的初始化
//将mid前的字符依次入栈
cout<<"栈中元素依次为(top指向栈顶,从上到下即从栈底到栈顶):"<<endl;
for(i=0;i<=mid;i++){
s[++top]=a[i];
cout<<"当前指向栈顶的top为:"<<top<<" ";
cout<<"s["<<top<<"]为"<<s[top]<<endl;
}
//判断字符串的长度时奇数还是偶数,并找出需要进行字符匹配的起始下标
if(len%2==0){//偶数
next=mid+1;
}
else{//奇数
next=mid+2;
}
cout<<endl;
cout<<"next为"<<next<<endl<<"即从字符a["<<next<<"]="<<a[next]<<"与栈顶元素开始匹配"<<endl;
cout<<endl;
//开始匹配
for(i=next;i<=len-1;i++){
if(a[i]!=s[top]){
break;
}
top--;
}
//如果top的值为0,则说明栈内所有的字符都被一一匹配了
if(top==0){
cout<<"该字符串是回文字符串";
}
else{
cout<<"该字符串不是回文字符串";
}
return 0;
}
/*
初始化栈时,top=0;
入栈操作:top++;s[top]=x(假设需要入栈的字符暂存在字符变量x中);
也可以简写为s[++top]=x;
*/
2.2解密回文——栈
最新推荐文章于 2022-05-31 14:20:35 发布