스택(stack)
후입선출 구조를 가진 알고리즘
function solution(s) {
const length = s.length;
// 길이가 홀수일 경우 올바른 괄호 쌍이 맞는 경우 없음
if(length%2 === 1) return 0;
const strArr = s.split('')
let count = 0;
// 왼쪽으로 한칸씩 이동
for(let i = 0; i<length; i++){
count += isValid(strArr,length)
strArr.push(strArr.shift())
}
return count;
}
const isValid = (array, length) => {
// 맞는 짝 찾으면 빼기
// 마지막에 빈 배열이 되어야 올바른 괄호
const stack = [];
const open = ['(','[','{'];
const close = [')',']','}'];
for(let i = 0; i<length; i++){
const now = array[i]
// array[i] 가 여는 괄호면 stack에 추가
if(open.includes(now)){
stack.push(now)
} else {
// 여는 괄호가 아닐 경우
// 스택의 마지막 값과 비교해 같으면 빼기
if(close.indexOf(now) === open.indexOf(stack[stack.length-1])){
stack.pop()
}
}
}
// stack이 남아있으면(=쌍이 맞지 않으면) 0 반환, 아니면 1 반환
return stack.length ? 0 : 1;
}
const arr = [1,2,3,1,2,3]
arr.indexOf(1) // 0
arr.lastIndexOf(3) // 5
includes() : 배열이 특정 값을 포함하고 있는지 여부를 boolean 값으로 반환
includes(x,y) : y인덱스 이후 x값을 포함하고 있는지 여부 판단