题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=2
第一次用栈来写的代码,早上队长讲了一下,了解了下基础,觉得C++的栈可以直接调用,C的栈却要自己定义,还是该花时间好好看C++.这是用C写的:
代码:
#include<stdio.h>
struct stack
{
char str[10005];
int top;
};
void Initstack(stack& a)//**构造一个空栈**//
{
a.top=-1;
}
void push(stack& a,char item)//**往栈里面插入一个新元素**//
{
a.top++;
a.str[a.top]=item;
}
void pop(stack& a)//**删除栈顶元素并返回其值**//
{
a.top--;
}
int main()
{
int s;
char ch;
scanf("%d",&s);
getchar();
while(s--)
{
stack a;
Initstack(a);
while(scanf("%c",&ch)&&ch!='\n')
{
if(ch=='['||ch=='(')
push(a,ch);
else
{
if(a.str[a.top]=='['&&ch==']')
{
pop(a);
}
else if(a.str[a.top]=='('&&ch==')')
{
pop(a);
}
else
{
push(a,ch);
}
}
}
if(a.top==-1)//**如果栈为空说明括号配对完成**//
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
return 0;
}
C++的STL:
#include<cstdio>
#include<stdio.h>
#include<stack>
#include<algorithm>
using namespace std;
int main()
{
int n;
char ch;
scanf("%d",&n);
getchar();
while(n--)
{
stack<char> s;
while(scanf("%c",&ch)&&ch!='\n')
{
if(s.empty())
{
s.push(ch);
}
else
{
if(ch=='('||ch=='[')
{
s.push(ch);
}
else
{
if(ch==']'&&s.top()=='[')
{
s.pop();
}
else if(ch==')'&&s.top()=='(')
{
s.pop();
}
else
{
s.push(ch);
}
}
}
}
if(s.empty())//**判断栈是否为空**//
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
return 0;
}
再贴一段:
#include<stdio.h>
struct stack
{
char str[10002];
int pos;
}s;
void push(char elem)//**往栈里面插入一个新元素**//
{
s.pos++;
s.str[s.pos]=elem;
}
void pop()//**删除栈顶元素并返回其值**//
{
s.pos--;
}
int main()
{
int n;
char ch;
scanf("%d",&n);
getchar();
while(n--)
{
s.pos=-1;//**空栈**//
while(scanf("%c",&ch)&&ch!='\n')
{
if(ch=='['||ch=='(')
push(ch);
else
{
if(ch==']'&&s.str[s.pos]=='['||s.str[s.pos]=='('&&ch==')')
{
pop();
}
else
{
push(ch);
}
}
}
if(s.pos==-1)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
return 0;
}
还有一段用数组做的,其实思想都一样。
#include <stdio.h>
int main()
{
int s,top;
scanf("%d",&s);
getchar();
while(s--)
{
top=0;
char a,str[20000];
while((a=getchar())!='\n')
{
if(a==')'&&top>0&&str[top-1]=='(')
{
top--;
}
else if(a==']'&&top>0&&str[top-1]=='[')
{
top--;
}
else
{
str[top++]=a;
}
}
if(top==0)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
return 0;
}
最后一段是比较完美的了:
#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
int main()
{
int n,len,i;
char str[10001];
scanf("%d",&n);
getchar();
while(n--)
{ stack<char> s;
scanf("%s",str);
len=strlen(str);
for(i=0;i<len;i++)
{
if(s.empty())s.push(str[i]);
else
{
if(s.top()+1==str[i]||s.top()+2==str[i])//**'('跟')'ASCII码差一,'['跟']'ASCII差二。**//
{
s.pop();
}
else
{
s.push(str[i]);
}
}
}
if(s.empty())
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
return 0;
}