题目描述
假设一个算术表达式中包含圆括号,方括号,花括号3种类型的括号,编写算法来判别表达式中括号是否配对。
输入
输入包含多组测试用例。
对于每组测试样例,包括一个仅由 ‘(’,’)’,’[’,’]’,’{’,’}'组成的字符串s。
输出
若s是合法的括号串,输出"yes",否则,输出"no"。
样例输入
[] ((()))
{()}(]
样例输出
yes
no
反思
一道括号匹配题,做完之后一直出现段错误。
原因是因为当输入"))"时,栈为空,我却调用了s.top(),此处非法。
// 题目:括号匹配
// 日期:2021/7/14
// 详情:假设一个算术表达式中包含圆括号,方括号,花括号3种类型的括号,
// 编写算法来判别表达式中括号是否配对。
// XWQ
#include <bits/stdc++.h>
using namespace std;
int Judge(string str){
stack<char> s;
if(str.size()==0)
return 1;
while(!s.empty())
s.pop();
for(int i=0; i<str.size(); i++){
if(str[i]=='(' || str[i]=='[' || str[i]=='{'){
s.push(str[i]);
}
else if(str[i]==')' && !s.empty()){
if(s.top()=='(') // !若栈未空,不能直接s.top,会段错误!
s.pop();
}
else if(str[i]==']' && !s.empty()){
if(s.top()=='[')
s.pop();
}
else if(str[i]=='}' && !s.empty()){
if(s.top()=='{')
s.pop();
}
else{
return 0;
}
}
return s.empty();
}
int main(){
string str;
while(cin>>str){
if(Judge(str))
printf("yes\n");
else
printf("no\n");
}
}