SWEA 나 프로그래머스, 백준 등등에서 많이 본 스택의 대표문제. 올바른 괄호인지 검증하는 문제였다.
function isValid(s: string): boolean {
const open = {"(": 1, "{": 2, "[": 3};
const close = {")": -1, "}": -2, "]": -3};
const stack = []
for (let i = 0; i < s.length; i++) {
if (stack.length === 0) {
stack.push(open[s[i]])
continue
}
if (open[s[i]]) {
stack.push(open[s[i]])
} else if (stack[stack.length - 1] + close[s[i]] === 0 ) {
stack.pop()
} else {
return false
}
}
return stack.length === 0 ? true : false
};