Parentheses Balance
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;
}
上一篇: 北京石油化工学院成立人工智能研究院
推荐阅读
-
【关于栈】Valid Parentheses详解
-
【关于栈】Valid Parentheses详解
-
平衡 balance
-
LeetCode - 20. Valid Parentheses(0ms)
-
当ERP遇上New Balance,玩转新零售商派有绝招!
-
Generate Parentheses(C++)
-
LeetCode-32.Longest Valid Parentheses最长有效括号子串
-
Longest Valid Parentheses leetcode java (求最长有效匹配括号子串的长度)-动态规划
-
算法分析与设计丨第一周丨LeetCode(2)——Different Ways to Add Parentheses(Medium)
-
kafka leader balance