세 가지 종류의 괄호로 이루어진 문자열이 주어지고 그 문자열을 회전시킬 수 있을 때, 올바른 괄호 문자열이 되는 경우의 수를 구하는 문제.
각 괄호별 여는 괄호 개수와 스택을 이용한 괄호 짝 검사를 통해 문자열이 올바른 괄호 문자열인지 알아낸다.
https://school.programmers.co.kr/learn/courses/30/lessons/76502
cpp code
#include <string>
#include <vector>
#include <stack>
#include <iostream>
using namespace std;
int cnt[256];
char counter[256];
bool check(string s) {
cnt['('] = cnt['{'] = cnt['['] = 0;
stack<char> S;
for (int i=0; i<s.length(); i++) {
char ch = s[i];
if (ch == '(' || ch == '{' || ch == '[') {
cnt[ch]++;
S.push(ch);
}
// ({[)}]
if (ch == ')' || ch == '}' || ch == ']') {
if (cnt[counter[ch]]-- == 0) {
return false;
}
if (counter[ch] != S.top()) {
return false;
}
else {
S.pop();
}
}
}
if (!S.empty()) return false;
else return true;
}
int solution(string s) {
counter[')'] = '(';
counter['}'] = '{';
counter[']'] = '[';
int ans = 0;
for (int i=0;i<s.length();i++) {
ans += check(s.substr(i) + s.substr(0, i));
}
return ans;
}