Programmers_괄호 회전하기

한상현·2021년 6월 21일
0

Algorithm

목록 보기
27/33

괄호를 돌려가며 유효한 괄호구성의 개수를 찾는 문제. 비교적 쉽게 풀어냈다.

  • 유효한 괄호 문자열인지 평가하는 bool 함수를 따로 만들어주고, string을 돌리며 함수를 통해 유효성을 검사했다.
  • 이게 다임...

전체코드

#include <string>
#include <vector>
#include <stack>

using namespace std;

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

int solution(string s) {
    int answer = 0;
    
    if(test(s)) answer++;
    
    for(int i=0;i<s.size()-1;i++)
    {
        s.push_back(s[0]);
        s.erase(0,1);
        if(test(s)) answer++;
    }
    
    return answer;
}
profile
의 공부 노트.

0개의 댓글