UVA-673 Parentheses Balance

来源:互联网 发布:淘宝买家怎么发微淘 编辑:程序博客网 时间:2024/06/06 04:43

2016-08-17

UVA - 673 Parentheses Balance

题目大意:匹配括号。空行也输出 Yes。

解题思路:左括号入栈,右括号出栈,最终栈空,输出 Yes。

注意:不能用计数偷懒,([(]))这种情况无法解决的。

([(])) ——> No

#include <iostream>#include <cstdio>#include <cstring>using namespace std;char str[150];char stack[150];int main() {int n;scanf("%d", &n);getchar();while ( n-- ) {memset (stack, '\0', sizeof(stack));gets(str);int len = strlen(str);int tag = 0;for (int i = 0; i < len; i++) {if ( str[i] == '(' || str[i] == '[' )stack[tag++] = str[i];if ( str[i] == ')' ) {if ( stack[tag-1] == '(' ) {stack[tag-1] = '\0';tag--;}else {stack[tag] = str[i];tag++;}}if ( str[i] == ']' ) {if ( stack[tag-1] == '[' ) {stack[tag-1] = '\0';tag--;}else {stack[tag] = str[i];tag++;}}}if ( stack[0] == '\0' )cout << "Yes" << endl;else cout << "No" << endl;}return 0;}


0 0
原创粉丝点击