405J1R训练四(T628215 括号匹配问题)

· · 个人记录

正确思路

先定个stack<int>s;再来个int b=0,c=0;再来个char a[300];然后来个while循环:

while(a[b]!='@'){
    b++; 
    cin>>a[b]; 
    if(a[b]=='(') {
        s.push(a[b]) ; 
        c++; 
    }
    if(a[b]==')' && c!=0){
        s.pop(); 
        c--; 
    }else if(a[b]==')' && c==0){
        cout<<"NO";
        return 0;
    }
} 

最后来个特判:

if(c==0){
    cout<<"YES";
}else{
    cout<<"NO";
}

正确代码

#include<bits/stdc++.h>
using namespace std ; 
stack<int>s; 
int b=0,c=0;
char a[300];  
int main(){
    while(a[b]!='@'){
        b++; 
        cin>>a[b]; 
        if(a[b]=='(') {
            s.push(a[b]) ; 
            c++; 
        }
        if(a[b]==')' && c!=0){
            s.pop(); 
            c--; 
        }else if(a[b]==')' && c==0){
            cout<<"NO";
            return 0;
        }
    } 
    if(c==0){
        cout<<"YES";
    }else{
        cout<<"NO";
    }
    return 0 ; 
}