假设以S
和X
分别表示入栈和出栈操作。如果根据一个仅由S
和X
构成的序列,对一个空堆栈进行操作,相应操作均可行(如没有出现删除时栈空)且最后状态也是栈空,则称该序列是合法的堆栈操作序列。请编写程序,输入S
和X
序列,判断该序列是否合法。
输入格式:
输入第一行给出两个正整数N和M,其中N是待测序列的个数,M(≤50)是堆栈的最大容量。随后N行,每行中给出一个仅由S
和X
构成的序列。序列保证不为空,且长度不超过100。
输出格式:
对每个序列,在一行中输出YES
如果该序列是合法的堆栈操作序列,或NO
如果不是。
输入样例:
4 10
SSSXXSXXSX
SSSXXSXXS
SSSSSSSSSSXSSXXXXXXXXXXX
SSSXXSXXX
输出样例:
YES
NO
NO
NO
代码:
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#define STACK_SIZE 51
using namespace std;
typedef int SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
int CreatS(SqStack &S)
{
S.base = (SElemType *)malloc(STACK_SIZE*sizeof(SElemType));
if(!S.base)
exit(-1);
S.top=S.base;
S.stacksize = STACK_SIZE;
return 1;
}
int GetTop(SqStack &S,SElemType &e)
{
if(S.top==S.base)
return 0;
e=*(S.top-1);
return 1;
}
int Push(SqStack &S,SElemType e)
{
if(S.top-S.base>=S.stacksize)
{
//S.base = (SElemType *)realloc(S.base,(S.stacksize+10)*sizeof(SElemType));
return 0;
}
*S.top++=e;
return 1;
}
int Pop(SqStack &S,char &e)
{
if(S.top==S.base)
return 0;
e=*--S.top; // e的存在是没有价值的!!记录删除的元素,本题中没有这个操作的必要
return 1;
}
int Empty(SqStack &S)
{
if(S.top==S.base)
return 1;
else
return 0;
}
int main()
{
int n,m;
cin>>n>>m;
while(n--)
{
string s;
cin>>s;
char e;
int len=s.length();
SqStack S;
CreatS(S);
int f=1;
int l=0;
for(int i=0;i<len;i++)
{
if(s[i]=='S')
{
Push(S,s[i]);
l++;
if(l>m)
{
cout<<"NO"<<endl;
f=0;
break;
}
}
else
{
if(Empty(S))
{
cout<<"NO"<<endl;
f=0;
break;
}
else
{
Pop(S,e);
l--;
}
}
}
if(f)
{
if(Empty(S))
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
}