💻 문제 출처 : 프로그래머스_괄호 회전하기
import java.util.*;
class Solution {
public int solution(String s) {
int answer = 0;
int sLength = s.length();
if(sLength % 2 == 1) return 0;
for(int i = 0; i < sLength; i++) {
Stack<Character> stack = new Stack<>();
int check = 0;
for(int j = 0; j < sLength; j++) {
char temp = s.charAt((i + j) % sLength);
if(temp == '[' || temp == '(' || temp == '{') {
stack.push(temp);
} else {
if(stack.isEmpty()) break;
char stackChar = stack.peek();
if((stackChar == '[' && temp == ']') || (stackChar == '(' && temp == ')') || (stackChar == '{' && temp == '}')) {
stack.pop();
check++;
}
}
}
if(check == sLength / 2) {
answer++;
}
}
return answer;
}
}
import java.util.Stack;
class Solution {
private final Stack<Character> stack = new Stack<>();
public int solution(String s) {
int answer = 0;
StringBuilder stringBuilder = new StringBuilder(s);
for (int i = 0; i < s.length(); i++) {
stringBuilder.append(stringBuilder.charAt(0));
stringBuilder.deleteCharAt(0);
if (correctParenthesis(stringBuilder.toString().toCharArray()))
answer++;
}
return answer;
}
private boolean correctParenthesis(char[] s) {
for (char c : s) {
if (!(check(c, '(', ')') && check(c, '[', ']') && check(c, '{', '}')))
return false;
}
return stack.isEmpty();
}
private boolean check(char c, char a, char b) {
if (c == a)
stack.push(a);
else if (c == b)
if (!stack.isEmpty() && stack.peek() == a) stack.pop(); else return false;
return true;
}
}