Post

[월간 코드 챌린지 시즌2] 괄호 회전하기 (C++)

https://school.programmers.co.kr/learn/courses/30/lessons/76502

풀이

Stack을 이용해 올바른 괄호를 찾아낸 후, string 함수를 이용해 문자열을 이동시켜줬다.

코드

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
27
28
29
30
31
32
#include <string>
#include <vector>
#include <stack>

using namespace std;

int solution(string s) {
    int cnt = 0;
    for(int i = 0; i < s.length(); i++){
        bool isRight = true;
        stack<char> st;
        for(char c : s){
            if(c == ')'){
                if(!st.empty() && st.top() == '(')  st.pop();
                else{   isRight = false;    break;  }
            }
            else if(c == ']'){
                if(!st.empty() && st.top() == '[')  st.pop();
                else{   isRight = false;    break;  }
            }
            else if(c == '}'){
                if(!st.empty() && st.top() == '{')  st.pop();
                else{   isRight = false;    break;  }
            }
            else    st.push(c);
        }
        if(isRight && st.empty())  cnt++;
        s += s[0];      s.erase(0, 1);
    }
    
    return cnt;
}
This post is licensed under CC BY 4.0 by the author.