Brackets! Brackets! hrbust (运用栈)
1 #include<stdio.h> 2 #include<string.h> 3 #define MAX 110 4 int main() 5 { 6 char stack[MAX]; 7 int top,n,i,flag; 8 char a[MAX]; 9 scanf("%d",&n); 10 while(n--) 11 { 12 top=-1; 13 flag=0; 14 scanf("%s",a); 15 for(i=0;i<strlen(a);i++) 16 { 17 if(a[i]=='('||a[i]=='['||a[i]=='{') 18 stack[++top]=a[i]; 19 else 20 { 21 if(top>=0&&((a[i]==')'&&stack[top]=='(')||(a[i]==']'&&stack[top]=='[')||(a[i]=='}'&&stack[top]=='{'))) 22 top--; 23 else 24 { 25 flag=1; 26 break; 27 }//注意这个语句的作用与下面的if的关系,你知道栈,但你不一定能很好的做这道题 28 } 29 } 30 if(!flag&&top==-1) 31 printf("Valid\n"); 32 else 33 printf("Invalid\n"); 34 } 35 return 0; 36 }
|
|||
Description | |||
There are six kinds of brackets: ‘(‘, ‘)’, ‘[‘, ‘]’, ‘{’, ‘}’. dccmx’s girl friend is now learning java programming language, and got mad with brackets! Now give you a string of brackets. Is it valid? For example: “(([{}]))” is valid, but “([)]” is not. |
|||
Input | |||
First line contains an integer T (T<=10): the number of test case. Next T lines, each contains a string: the input expression consists of brackets. The length of a string is between 1 and 100. |
|||
Output | |||
For each test case, output “Valid” in one line if the expression is valid, or “Invalid” if not. |
|||
Sample Input | |||
2 {{[[(())]]}} ({[}]) |
|||
Sample Output | |||
Valid Invalid |