You are given a string consisting of parentheses () and []. A string of this type is said to becorrect:
- (a)
- if it is the empty string
- (b)
- if A and B are correct, AB is correct,
- (c)
- if A is correct, (A ) and [A ] is correct.
Write a program that takes a sequence of strings of this type and check their correctness. Your program can assume that the maximum string length is 128.
The file contains a positive integer n and a sequence of n strings of parentheses() and [], one string a line.
A sequence of Yes or No on the output file
3
([])
(([()])))
([()[]()])()
Yes No Yes
题意:给定一字符串s,判断'('和')','['和']'是否成对出现,如果是则为Yes,否则为No;
字符串为空时也为Yes. 使用栈,是'('和'['时,maze.push(),进栈,
如果是')'和']',判断是否有对应的'('和'['来maze.pop(),否则为No;
给出
#include<stdio.h>
#include<string.h>
#include<stack>
#include<algorithm>
using namespace std;
char a[110];
You are given a string consisting of parentheses () and []. A string of this type is said to becorrect:
- (a)
- if it is the empty string
- (b)
- if A and B are correct, AB is correct,
- (c)
- if A is correct, (A ) and [A ] is correct.
Write a program that takes a sequence of strings of this type and check their correctness. Your program can assume that the maximum string length is 128.
The file contains a positive integer n and a sequence of n strings of parentheses() and [], one string a line.
A sequence of Yes or No on the output file
3([])
(([()])))
([()[]()])()
Yes
No
Yes
题意:给定一字符串s,判断'('和')','['和']'是否成对出现,如果是则为Yes,否则为No;
字符串为空时也为Yes. 使用栈,是'('和'['时,maze.push(),进栈,
如果是')'和']',判断是否有对应的'('和'['来maze.pop(),否则为No;
给出代码:
#include<stdio.h>
#include<string.h>
#include<stack>
#include<algorithm>
using namespace std;
char a[110];
int main()
{
int f,i,flag,l;
scanf("%d",&f);
getchar();
while(f--){
memset(a,'\0',sizeof(a));
stack<char> maze; //一定要注意数组和栈的初始化,不然会WA
gets(a); //注意gets()录入
l=strlen(a);
flag=0;
for(i=0;i<l;i++){
if(a[i]=='('||a[i]=='[')
maze.push(a[i]);
else if(a[i]==')'){
if(!maze.empty()&&maze.top()=='(')
maze.pop();
else{
flag=1;
break;
}
}
else if(a[i]==']'){
if(!maze.empty()&&maze.top()=='[')
maze.pop();
else{
flag=1;
break;
}
}
}
if(flag==1||!maze.empty())
printf("No\n");
else
printf("Yes\n");
}
return 0;
}
今天2018 高考结束。心情不好