Queue 를 이용하여 회전하는 로직을 구현하였고,
회전을 1회 할때마다 isValid 함수를 통해 유효한 괄호인지 체크하였다.
isEmpty() 를 리턴하여 stack이 비었다면 true를 리턴하도록 구현하였다.
import java.util.*;
class Solution {
public int solution(String s) {
int answer = 0;
Queue<Character> q = new ArrayDeque<>();
for(int i = 0 ; i < s.length(); i++)
q.offer(s.charAt(i));
for(int i = 0 ; i < s.length(); i++){
if(isValid(q))
answer++;
q.offer(q.poll());
}
return answer;
}
public boolean isValid(Queue<Character> q){
Stack<Character> st = new Stack<>();
for(Character c : q){
if(c == '(' || c == '{' || c == '[')
st.add(c);
else{
if(st.isEmpty())
return false;
Character top = st.pop();
if((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '['))
return false;
}
}
return st.isEmpty();
}
}
'Algorithm & Data Structures > Programers' 카테고리의 다른 글
Lv 2. [3차] 압축 (0) | 2024.06.30 |
---|---|
Lv 2. N진수게임 (0) | 2024.06.28 |
Lv 2. 게임 맵 최단거리 (0) | 2024.06.23 |
Lv 2. pK진수에서 소수 개수 구하기 (0) | 2024.06.22 |
Lv 2. 타겟 넘버 (0) | 2024.06.20 |