9012번 - 괄호(C++)

Duna·2020년 10월 8일
0

1️⃣ 괄호 첫 번째 시도 ❌

stackCount를 사용해서 '('의 경우에는 count가 1 증가하고 ')'는 1 감소하도록 했다. stackCount가 결론적으로 0이 나오면 제대로 실행이 된다는 것, 하지만 예외의 경우가 존재했다.

⭐️ ())(() : 이 경우에는 결론적으로 0이 나오지만 잘못된 괄호라고 볼 수 있다.

#include <iostream>
#include <string>

using namespace std;

int main() {
    int caseNumber = 0, caseCount = 0;
    
    cin >> caseNumber;
    
    while(1) {
        if(caseCount == caseNumber) break;
        else caseCount++;
        
        int stackCount = 0;
        string parenthesis;
        
        cin >> parenthesis;
        
        for(int i = 0; i < parenthesis.length(); i++){
            if(parenthesis[i] == '(') stackCount++;
            else stackCount--;
        }
        
        if(stackCount == 0) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
}

2️⃣ 괄호 두 번째 시도 ⭕️

이번에는 stack이라는 배열을 만들어서 '('가 나올 때 넣어주고 아닐 땐 빼주는 식의 stack의 역할을 하도록 했다. 아까 코드와는 다르게 제대로 된 결과를 내보냈다.

#include <iostream>
#include <string>

using namespace std;

int main() {
    int caseNumber = 0, caseCount = 0;
    
    cin >> caseNumber;
    
    while(1) {
        if(caseCount == caseNumber) break;
        else caseCount++;
        
        int stackCount = 0;
        bool isVaild = true;
        char stack[50];
        string parenthesis;
        
        cin >> parenthesis;
        
        for(int i = 0; i < parenthesis.length(); i++){
            if(parenthesis[i] == '('){
                stack[stackCount++] = parenthesis[i];
            }
            else if(parenthesis[i] == ')' && stackCount != 0)
                stack[stackCount--] = '\0';
            else if(parenthesis[i] == ')' && stackCount == 0) {
                isVaild = false;
                break;
            }
        }
        
        if(stackCount != 0) isVaild = false;
        
        if(isVaild) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
}

3️⃣ 괄호 세 번째 시도 ⭕️

stack를 사용하는 방법인데, 위의 식보다 코드를 이해하기 쉽다는 장점이 있는 거 같다. 실제 stack에서 사용하는 push, pop, empty를 따로 함수로 구현하지 않아도 사용할 수 있다. 해당 코드도 제대로 된 결과를 냈다. 걸린 시간은 위의 코드와 동일했다.

#include <iostream>
#include <stack>
#include <string>

using namespace std;

bool parenCheck(string parenthesis){
    stack<char> parenStack;
    
    for(int i = 0; i < parenthesis.length(); i++){
        char c =  parenthesis[i];
        
        if(c == '(')
            parenStack.push(parenthesis[i]);
        else if(c == ')' && !parenStack.empty())
            parenStack.pop();
        else if(c == ')' && parenStack.empty())
            return false;
    }
    
    if(parenStack.empty()) return true;
    else return false;
}

int main() {
    int caseNumber = 0, caseCount = 0;
    
    cin >> caseNumber;
    
    while(1) {
        if(caseCount == caseNumber) break;
        else caseCount++;
        
        string parenthesis;
        
        cin >> parenthesis;
        
        if(parenCheck(parenthesis)) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
}
profile
더 멋진 iOS 개발자를 향해

0개의 댓글