프로그래밍/알고리즘 풀이
[node.js] 괄호 회전하기 ( 프로그래머스 레벨2 )
카카수(kakasoo)
2021. 7. 1. 22:44
반응형
const left = 0;
const right = 1;
const isRight = (arr) => {
const stack = [];
for (const item of arr) {
stack.push(item);
if (stack.length >= 2) {
while ((stack[stack.length - 2] === '(' && stack[stack.length - 1] == ')') ||
(stack[stack.length - 2] === '[' && stack[stack.length - 1] == ']') ||
(stack[stack.length - 2] === '{' && stack[stack.length - 1] == '}')) {
stack.pop();
stack.pop();
}
}
}
return stack.length ? false : true;
}
const solution = (s) => {
const strArr = s.split('');
let i = strArr.length;
let count = 0;
while(i--) {
strArr.push(strArr.shift());
if(isRight(strArr)) {
count++;
}
}
return count;
}
회전하는 것은 문자열 길이 만큼을 해야 하며, ( do while문으로 짰다면 length - 1 까지만 해도 된다. )
돌면서 올바른 괄호 문자열이 맞는지 체크해줘야 한다.
isRight 함수는 stack을 만들고 그 안에 계속 문자를 push하며 올바른 경우마다 2개 씩 pop한다.
마지막에 모든 문자가 pop되서 사라지면 ok, 사라지지 않으면 올바르지 않은 경우이다.
반응형