[스택] 괄호 회전하기

조은지·2021년 4월 18일
0
#include <string>
#include <vector>
#include <stack>

using namespace std;

int solution(string s) {
    int answer = 0;
    int check = 0;
    stack<char> bucket;
    int i=0,j=0;
    int length = s.size();
    if(length%2==1){
        return 0;
    }
    for(i=0;i<length;i++){
        check=0;
        for(j=0;j<length;j++){
            if(s[j]=='{'||s[j]=='['||s[j]=='('){
                bucket.push(s[j]);
            }
            else if(s[j]=='}'&& bucket.top()=='{'){
                bucket.pop();
                check++;
            }
            else if(s[j]==']'&& bucket.top()=='['){
                bucket.pop();
                check++;
            }
            else if(s[j]==')'&& bucket.top()=='('){
                bucket.pop();
                check++;
            }

        }
        if(check == length/2){
            answer++;
        }
        s += s[0];
        s = s.substr(1);   
        while(!bucket.empty()){
            bucket.pop();
        }
    }
    return answer;
}

문자열의 길이/2가 만족이 되면 answer++을 추가하는 식으로 구현을 했다.
이 때, 문자열의 길이가 홀수이면 회전하더라도 모든 괄호를 만족시키지 못하기 때문에 바로 0을 리턴하도록 했다.

0개의 댓글

관련 채용 정보