[프로그래머스/C++] 괄호 회전하기

최대 1 분 소요

1.문제 링크

괄호 회전하기



2. 풀이 전 계획과 생각

  • stack 이용



3. 풀이

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

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

int solution(string s) {
    int answer = 0;
    string str = s;
    for(int i=0;i<s.size();i++){
        str = str + str[0];
        str.erase(0,1);
        if(IsRight(str)) answer++;
    }

    return answer;
}

string s 크기만큼 반복하면서 괄호를 회전한다.

스택을 이용해 올바른 괄호인지 판단한다.



4. 풀이하면서 고민했던 점



5. 문제를 풀고 알게된 개념 및 소감

  • string의 erase메소드 사용법을 알게됨.