【HRBUST - 1054 】Brackets! Brackets! (括号匹配,思维,STL栈)

版权声明:欢迎学习我的博客,希望ACM的发展越来越好~ https://blog.csdn.net/qq_41289920/article/details/82944741

题干:

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


{{[[(())]]}} 
({[}])

Sample Output

Valid 
Invalid

解题报告:

    水题模拟不解释。就是找到关键元素在于,对于第一个出现的右括号,与之相邻的一定是左括号,抓住这一点,程序很好写了。

AC代码:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
bool iszuo(char ch) {
	return ch=='(' || ch=='[' || ch=='{';
}
bool isyou(char ch) {
	return ch==')' || ch==']' || ch=='}';
} 
char s[1005];
int main() 
{
	int t;
	cin>>t;getchar();
	while(t--) {
		stack<char> sk;
		//getline(cin,s);
		cin.getline(s,1005);
		int len = strlen(s);
		int flag = 1;
		for(int i = 0; i<len; i++) {
			if(iszuo(s[i])) sk.push(s[i]);
			else {
				if(sk.empty()) {
					flag=0;break;
				}
				if(s[i] ==')') {
					if(sk.top() != '(') {
						flag=0;break;
					}
				}
				else if(s[i] == ']') {
					if(sk.top() != '[') {
						flag=0;break;
					}
				}
				else {
					if(sk.top() != '{') {
						flag=0;break;
					}
				}
				sk.pop();
			}
		}
		if(flag && sk.empty()) puts("Valid");
		else puts("Invalid");
	}
	return 0;
}

总结:

   虽然是一道水题但是还是有很多值得总结的地方。比如要时刻看看是否栈为空,包括最后输出的地方,因为栈不空时,显然是invalid的情况!

   还有就是因为整个就在用sk.top()和s[i]这两个值,所以别用错了,比如有个地方的sk.top()我就写成了s[i]

猜你喜欢

转载自blog.csdn.net/qq_41289920/article/details/82944741