이런 느낌으로 풀어봐야하나

#include <iostream>
#include <stack>
using namespace std;

int main(){
    int T;
    cin >> T;
    while(T--){
        string line;
        stack<char>s;
        cin >> line;
        for(auto x : line){
            if(s.empty()) s.push(x);
            else if(s.top() != x) s.pop();
            else s.push(x);
        }
        if(s.empty()) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}

 

이러면

(()())((()))

이거 입력했을 때

)( 이거도 서로 다른거니까 pop 해서

NO 나와야되는데 YES 나옴

#include <iostream>
#include <stack>
using namespace std;

int main(){
    int T;
    cin >> T;
    while(T--){
        string line;
        stack<char>s;
        cin >> line;
        for(auto x : line){
            if(s.empty()) s.push(x);
            else if(s.top() == '(' && x == ')') s.pop();
            else s.push(x);
        }
        if(s.empty()) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}

 이렇게 바꾸니까 성공!

+ Recent posts