3664 - 括号判断
在数学表达式中经常会看见括号,除去数字和运算符,就只剩下括号了。我们知道像(),[],[[]],(()[])这样的括
号是正确的,而像(],][,[][(]),[,[[][])这样的括号用法是错误的,现在有一串括号,只包含‘[’‘]’‘(’‘)’这四个字
符,判断他们是否正确。像([])也是对的
Input
每个测试占一行,每行只有‘[’‘]’‘(’‘)’这四个字符每行的字符不超过20,且保证每行后都有一个回车符
<span></span>
Output
对于每个测试数据,如果括号用法是对的,就输出”Yes”,否则输出”No”,
Examples
Input
([[]()]) [][(])
Output
Yes No
Solution C
#include <stdio.h> #include <string.h> #define MAX 26 int main() { char _stack[MAX]; int top; char a[30]; while (scanf("%s", &a) != EOF) { top = -1; for (int i = 0; i<strlen(a); i++) { //栈非空 if (top != -1) { //出栈 if (_stack[top] == '('&&a[i] == ')' || _stack[top] == '['&&a[i] == ']') top--; else{ _stack[++top] = a[i]; } } else{ _stack[++top] = a[i]; } } if (top == -1) { printf("Yes\n"); } else printf("No\n"); } return 0; }
Solution C++
#include <stdio.h> #include <stack> #include <string.h> using namespace std; int main() { int len,i,check; char a[50],c; while(gets(a)) { stack<char > que; que.push('b'); check=1; len=strlen(a); for(i=0;i<len;i++) { if(a[i]=='('||a[i]=='[') { que.push(a[i]); continue; } else if(a[i]==')'||a[i]==']') { if(a[i]==')') { if(que.top()=='(') { que.pop(); continue; } else { check=0; break; } } if(a[i]==']') { if(que.top()=='[') { que.pop(); continue; } else { check=0; break; } } } } if(check&&que.size()==1) printf("Yes\n"); else printf("No\n"); } return 0; }