NYOJ 2 括号配对问题 数据结构栈的应用
来源:互联网 发布:淘宝秀福利 编辑:程序博客网 时间:2024/06/06 23:57
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <stack>using namespace std ;const int MAXN = 10005 ;char str[MAXN] ;bool flag ;void judge (){ int i ; int len ; char ch ; stack <char> Q ; len = strlen (str) ; for (int i = 0; i < len; i ++) { if (Q.empty()) { Q.push (str[i]) ; continue ; } if (str[i] == '[' || str[i] == '(') Q.push (str[i]) ; else { if (str[i] == ']') { ch = Q.top () ; Q.pop () ; if (ch != '[') { flag = false ; return ; } } else { ch = Q.top () ; Q.pop () ; if (ch != '(') { flag = false ; return ; } } } } if (!Q.empty ()) // 如果此时栈中还有元素,肯定不匹配 { flag = false ; Q.pop () ; } return ;}int main(){ int tcase ; scanf ("%d", &tcase) ; while (tcase --) { scanf ("%s", str) ; flag = true ; judge () ; if (flag) printf ("Yes\n") ; else printf ("No\n") ; memset (str, '\0', sizeof(str)) ; } return 0 ;}