基于栈的回文字符序列判断

#include <iostream>
#define MAXSIZE 10000
#include<string>
using namespace std;

typedef struct 
{
	char *base;
	char *top;
	int stacksize;
	
 }SqStack;
 
 int InitStack(SqStack &S)
 {
 	if(!S.base) return 0;
 	S.base=new char [MAXSIZE];
 	S.top=S.base;
 	S.stacksize=MAXSIZE;
 	return 1;
 }
 
int Push(SqStack &S,char e)
{
	if(S.top-S.base==S.stacksize)return 0;//cout<<"PUSH ERROR"<<endl;
	*S.top=e;
	S.top++;
	return 1;
}

int GetTop(SqStack S)
{
	if(S.top!=S.base)
		return *(S.top-1);
}

int Pop(SqStack &S,char &e)
{
	if(S.top==S.base)
	{
		cout<<"POP ERROR"<<endl;
		return 0;
	}
	//cout<<GetTop(S)<<endl;
	S.top--;
	e=*S.top;
	//cout<<"e:"<<e<<endl;
	return 1;
}

int main()
{
	
	int n=0;int num;char temp;
	while(1)
	{	
		SqStack S;
		InitStack(S);
		string str;int i;
		cin>>str;
		if(str=="0")break;
		n=str.length();

			//cout<<n<<endl;
			for(i=0;i<n/2;i++)
			{
				//cout<<"i:"<<i<<endl;
				Push(S,str[i]);
			}
			if(n%2!=0) i++;
			//cout<<"i:"<<i<<endl;
			while(i<n)
			{
				char e='c';
				//cout<<"temp:"<<temp<<endl;
				//cout<<"i:"<<i<<"stri:"<<str[i]<<endl;
				Pop(S,e);
				temp=e;
				if(temp!=str[i])
				{
					//cout<<str<<endl;
					//cout<<"!!!	"<<temp<<"	***	"<<str[i]<<"	!!!"<<endl;
					cout<<"NO"<<endl; 
					break;
				}
				if(i==n-1)
				{
					cout<<"YES"<<endl;
					break;
				}
				i++;
				//cout<<"i:"<<i<<"stri:"<<str[i]<<endl;	
			}	
			
	}
	return 0;
}

描述

回文序列是正反读均相同的字符序列,如“abba”和“abdba”均是回文,但是“good”不是回文。请设计一个算法判定给定的字符序列是否为回文。

输入

多组数据,每组数据有一行。每一行为一个长度不定的字符序列A。当A为“0”时,输入结束。

输出

对于每组数据输出一行。若字符序列A是回文序列,则输出“YES”,否则输出“NO”。

输入样例 1 

abba
abdba
good
0

输出样例 1

YES
YES
NO
发布了100 篇原创文章 · 获赞 4 · 访问量 3691

猜你喜欢

转载自blog.csdn.net/weixin_43673589/article/details/104390708