- 난이도: Lv2
프로그래머스 링크: https://school.programmers.co.kr/learn/courses/30/lessons/76502
풀이 링크(GitHub): hayannn/CodingTest_Java/프로그래머스/2/괄호 회전하기
풀이 시간 : 22분
import java.util.*;
public class Solution {
static public int solution(String s) {
int answer = 0;
for (int i = 0; i < s.length(); i++) {
Stack<Character> stack = new Stack<>();
String rotatedStr = s.substring(i) + s.substring(0, i);
for (char c : rotatedStr.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else if (!stack.isEmpty() && isValidPair(stack.peek(), c)) {
stack.pop();
} else {
stack.push(c);
}
}
if (stack.isEmpty()) {
answer++;
}
}
return answer;
}
static boolean isValidPair(char open, char close) {
return (open == '(' && close == ')') ||
(open == '{' && close == '}') ||
(open == '[' && close == ']');
}
}