欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Parentheses Balance

程序员文章站 2022-05-22 15:03:16
...

Description:
You are given a string consisting of parentheses () and []. A string of this type is said to be correct:
(a) if it is the empty string
(b) if A and B are correct, AB is correct,
© if A is correct, (A) and [A] is correct.
Write a program that takes a sequence of strings of this type and check their correctness. Your program can assume that the maximum string length is 128.
Input
The file contains a positive integer n and a sequence of n strings of parentheses ‘()’ and ‘[]’, one string
a line.
Output
A sequence of ‘Yes’ or ‘No’ on the output file.
Sample Input
3
([])
(([()])))
([()])()
Sample Output
Yes
No
Yes

利用STL中的栈比较容易解决。
stackname;声明一个T类型的名称为name的栈。
注意因为空串应该输出Yes,所以不可以用string读入表达式,它会跳过空格,换行符。这里利用的是gets来读入,通过判断读入的字符串是否等于换行符来解决空串。此外,我用的是cin>>n;所以要用getchar()将回车滤掉,要不然输入n后换行就会输出Yes。

表达式中如果是左括号则进栈,若是右括号则取出栈顶元素判断是否和这个右括号匹配,注意!先判断栈是否是非空的才可以进行取元素操作。

#include<iostream>
#include<stack>
#include<cstring>
#include<string>
using namespace std;
stack<char>exp;
int main(){
	int n;
	cin>>n;
	getchar();//滤掉一个空格 
	char s[200];
	while(n--){
		int flag=1;
		gets(s);//判断是否是空串,不能用string了 
		if(strcmp(s,"\n")==0){
			cout<<"Yes"<<endl;
			continue;
		}
//		int len=s.length();
		for(int i=0;s[i];i++){
			if(s[i]=='['||s[i]=='(')
				exp.push(s[i]);
			else if(s[i]==']'){
				if(exp.empty()){
					flag=0;
					break;
				}
				char ch=exp.top();
				if(ch=='[')
					exp.pop();
			}
			else if(s[i]==')'){
				if(exp.empty()){
					flag=0;
					break;
				}
				char ch=exp.top();
				if(ch=='(')
					exp.pop();
			}
		}
		if(!exp.empty())
			flag=0;
		if(flag)
			cout<<"Yes"<<endl;
		else
			cout<<"No"<<endl;
		while(!exp.empty())
			exp.pop();
	}
	return 0;
}
相关标签: stack