🍞 Problem Solving/Programmers

[프로그래머스][Level2] 올바른 괄호 c++

박빵이 2022. 10. 21. 12:49

풀이 과정

) 일 때 스택이 비어있거나, top이 (이 아니라면 올바르지 않은 괄호이다.  
또한, 반복문을 다 돌았을 때 스택에 남아있는 것들이 있다면 올바르지 않은 괄호이다.

 

풀이 1

#include <string>
#include <stack>

using namespace std;

bool solution(string s)
{
    bool answer = true;
    stack<char> st;
    for(int i = 0; i < s.size(); i++){
        if(s[i] == ')'){
            if(!st.empty() && st.top() == '(') st.pop();
            else answer = false;
        }
        else st.push('(');
    }
    if(!st.empty()) answer = false;

    return answer;
}

 

풀이 2

#include <string>
#include <stack>
#define STACK_SIZE 100001

using namespace std;

int st[STACK_SIZE];
int top = -1; // 스택은 공백상태일 때 top이 -1

// empty() 함수 구현
bool IsEmpty(){
    if(top < 0) return true;
    else return false;
}
// full() 함수 구현
bool IsFull(){
    if(top >= STACK_SIZE - 1) return true;
    else return false;
}
// push() 함수 구현
void push(char c){
    if(!IsFull()) st[++top] = c;
}
// pop() 함수 구현
void pop(){
    if(!IsEmpty()) st[top--];
}
// top() 함수 구현
int peek(){
    if(!IsEmpty()) return st[top];
}
// size() 함수 구현
int size(){
    return top + 1;
}

bool solution(string s)
{
    bool answer = true;
    for(int i = 0; i < s.size(); i++){
        if(s[i] == ')'){
            if(!IsEmpty() && peek() == '(')
                pop();
            else answer = false;
        }
        else push('(');
    }
    if(!IsEmpty()) answer = false;

    return answer;
}