스택을 활용하는 올바른 괄호 찾기 문제이다.
그런데 어제 프로그래머스에서 풀이한 연속 부분 수열 합의 개수 문제에서 처럼 회전하는 벡터를 활용하는 부분이 있다.
https://velog.io/@magicdrill/%EC%97%B0%EC%86%8D-%EB%B6%80%EB%B6%84-%EC%88%98%EC%97%B4-%ED%95%A9%EC%9D%98-%EA%B0%9C%EC%88%98
오늘 현대 NGV 과정 중 C언어로 이것저것 할때도 비슷한 문제가 있었던 거 같다.
import java.util.*;
class Solution {
public int solution(String s) {
int answer = -1, count = 0;
int i, j, current, length = s.length(), k;
char parentheses;
for(i = 0; i < length; i++){
Stack <Character> st = new Stack <>();
//왼쪽으로 i만큼 회전했다고 치고,
for(j = 0; j < length; j++){
current = (j + i) % length; //회전한 인덱스
parentheses = s.charAt(current);// 해당 인덱스의 괄호 문자
//System.out.print(current + " ");
System.out.print(parentheses + " ");
if(st.isEmpty()){//스택이 비어있으면 바로 추가
st.push(parentheses);// java의 스택 추가는 push
}
else if(st.peek() == '[' && parentheses == ']'){//스택의 머리 값 확인
st.pop();
}
else if(st.peek() == '(' && parentheses == ')'){
st.pop();
}
else if(st.peek() == '{' && parentheses == '}'){
st.pop();
}
else{
st.push(parentheses);
}
}
if(st.isEmpty()){
System.out.print (" O ");
count++;
}
else{
System.out.print(" X ");
}
System.out.println();
}
answer = count;
return answer;
}
}