UVA-673 Parentheses Balance

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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章