You are given a string consisting of parentheses () and []. A string of this type is said to be correct:
- (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.
Input
The file contains a positive integer n and a sequence of n strings of parentheses () and [], one string a line.
Output
A sequence of Yes or No on the output file.
Sample Input
3 ([]) (([()]))) ([()[]()])()
Sample Output
Yes No Yes
代码如下:
1 #include<iostream> 2 #include<stdio.h> 3 #include<stack> 4 #include<string.h> 5 using namespace std; 6 7 int main() 8 { 9 int n; 10 while(scanf("%d",&n)!=EOF) 11 { 12 char stack[128]; 13 char str[128]; 14 getchar(); //由于gets()把换行符当做结束字符,注意用getchar()吸收换行符。 15 while(gets(str)) 16 { 17 18 int i,top=-1; 19 for(i=0;i<strlen(str) ;i++) 20 { 21 if(str[i]==‘(‘|| str[i]==‘[‘) 22 stack[++top]=str[i]; 23 24 25 if(str[i]==‘)‘ && stack[top]!=‘(‘) 26 { 27 top=0; 28 break; 29 } 30 else if(str[i]==‘]‘ && stack[top]!=‘[‘) 31 { 32 top=0; 33 break; 34 } 35 36 if(str[i]==‘)‘ && stack[top]==‘(‘) 37 top--; 38 39 else if(str[i]==‘]‘ && stack[top]==‘[‘) 40 top--; 41 42 43 } 44 45 if(top==-1) 46 printf("Yes\n"); 47 else 48 printf("No\n"); 49 } 50 } 51 52 return 0; 53 }
本来要求是要自己实现栈的操作,可是不熟悉自己写不了,只好用STL暂时先过了题。还参考了大神的代码,看了好几天的书百度很多栈的相关用法,栈的数组表示和栈的代码实现。虽说已经学了一年的C和C++,可感觉自己很不熟悉对于竞赛题恐惧极了。现在在重新补充学习C和C++。无论怎样,每天都要比昨天的自己懂得更多,即使进步微乎其微,也不要轻易放弃。看不见希望是很恐怖难过的事,不被看好也没关系,自己啊,要握住生命的绳不被左右不被打乱pace。
第二周马上要结束了,好好总结。恩。
时间: 2024-12-10 06:28:34