我的猫子叫小花 2021-04-14 17:48 采纳率: 100%
浏览 66
已结题

7-3 括号匹配 总有一个测试点过不了

#include<bits/stdc++.h>
#include<string>
using namespace std;
int main(){
    int flag=1;
    stack<char> s;
    stack<char,vector<char> > stk;
    string str;
    getline(cin,str);
    for(int i=0;i<str.size();i++){
        if(str[i]=='{'||str[i]=='['||str[i]=='('){
            s.push(str[i]);
        }
        else if(str[i]=='}'){
            if(!s.empty()){
                if(s.top()!='{'){
                cout<<"no";
                    flag=0;
                    break;
                }
                else s.pop();
                }
                else{
                    flag=0;
                    break;
                }
        }
        else if(str[i]==']'){
            if(!s.empty()) {
                if(s.top()!='['){
                cout<<"no";
                flag=0;
                    break;
                }
               else s.pop();
            }
            else{
                    flag=0;
                    break;
                }
        }
         else if(str[i]==')'){
            if(!s.empty()) {
                if(s.top()!='('){
                cout<<"no";
                    flag=0;
                    break;
                }
                else s.pop();
                }
            else{
                    flag=0;
                    break;
                }
        }
    }
    if(flag==1){
    if(s.empty()) cout<<"yes";
    else cout<<"no";
    }
    return 0;
}

 

  • 写回答

1条回答 默认 最新

  • 爱编程的小芒果 2023-07-13 15:28
    关注

    这题我以前做过,但我突然找不到代码了,我记得当时我用的是暴力还是搜索来着。就是从第一个开始循环,遇到匹配的都给他赋值为-1,然后循环时判断一下该位置是不是-1在找匹配,希望对你有帮助。如果有帮助的话,能采纳吗?

    本回答被专家选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月18日
  • 专家已采纳回答 8月10日