Algorithm/C++ - 프로그래머스

프로그래머스 level2 - 올바른 괄호 C++

ㅇㅇ잉 2021. 4. 5. 09:51

풀이

1. 여는 괄호('(')가 나오면 stack에 push

2. 닫는 괄호(')')가 나오면 stack에서 pop

이때 stack이 비어있거나, 문자열 길이만큼의 for문 연산이 끝났음에도 stack이 비어있지 않다면 false를 return해준다.

그외에는 true return.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<string>
#include <iostream>
#include <stack>
 
using namespace std;
 
bool solution(string s)
{
    stack<int> st;
    bool answer = true;
    for(int i=0;i<s.length();i++){
        if(s[i]=='('){
            st.push(s[i]);
        }
        else if(s[i]==')'){
            if(st.empty()){
                return false;
            }
            else{
                st.pop();
            }
        }
    }
    if(!st.empty()) return false;
    return answer;
}
cs

 

 

문제를 풀고 나서 다른 풀이도 봤는데, stack말고 그냥 변수를 이용해서 푸는 방법도 괜찮은 것 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<string>
#include <iostream>
#include <stack>
 
using namespace std;
 
bool solution(string s)
{
    int n=0;
    for(int i=0;i<s.length();i++){
        if(n<0return false;
        if(s[i]=='('){
            ++n;
        }
        else if(s[i]==')'){
            --n;
        }
    }
    return n==0;
}
cs