Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
올바른 괄호인지 확인하고, 맞다면 true 아니면 false를 반환한다.
()[]{}
true
pop()
하여 없앤다.var isValid = function(s) {
let answer = true;
const map = {
'(' : ')',
'{' : '}',
'[' : ']'
};
const stack = [];
const open = Object.keys(map); // ["(", "{", "["]
// 짝수가 아니면 리턴
if (s.length % 2 !== 0) return false;
for (let x of s) {
// x가 열린 괄호인가? 그럼 스택에 넣는다.
if(open.includes(x)) stack.push(x);
else { // x는 닫힌 괄호
// stack의 마지막 열린 괄호의 value와 x가 같다면
// stack 마지막 열린 괄호 pop
if (map[stack[stack.length - 1]] === x) stack.pop();
else return false;
}
}
return answer;
};