const solution = (s) => {
const stack = [];
for (let i = 0; i < s.length; i++) {
const current = s[i];
if (stack.length == 0) {
stack.push(current);
continue;
}
const previous = stack.pop();
if (current == previous) {
continue;
}
stack.push(previous, current);
}
if (stack.length == 0) {
return 1;
}
return 0;
};
스택을 이용하면 O(n)으로도 끝나는구나...
아래는 다른 사람의 풀이를 참고하여 좀 더 간결하게 재구성한 코드
const solution = (s) => {
const stack = [];
for (let i = 0; i < s.length; i++) {
const current = s[i];
const previous = stack[stack.length - 1];
if (current == previous) {
stack.pop();
continue;
}
stack.push(current);
}
if (stack.length == 0) {
return 1;
}
return 0;
};