题解 | #检查给定字符串中的多种括号是否匹配#

检查给定字符串中的多种括号是否匹配

http://www.nowcoder.com/questionTerminal/d4a0434b32d341b0941b75fd1ba75aab

#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
int main(){
    string ans="true",str;
    char couple;
    cin>>str;
    stack<char>s;
    for(int i=0;i<str.size();i++)
        if (str[i]=='('||str[i]=='['||str[i]=='{')s.push(str[i]);
        else if(str[i]==')'||str[i]==']'||str[i]=='}'){
            if (str[i]==')')couple='(';
            else if(str[i]==']')couple='[';
            else couple='{';
            if(s.empty()||s.top()!=couple){
                ans="false";
                break;
            }else s.pop();
        }
    if(!s.empty())ans="false";
    cout<<ans<<endl;
    return 0;
}


全部评论

相关推荐

2025-12-03 22:15
山东交通学院 Java
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务