Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "([)]"
Output: false
push
한다.pop
한다.false
를 반환한다.true
를, 그렇지 않다면 false
를 반환한다.var isValid = function(s) {
const arr = s.split("");
const stack = [];
let answer = true;
if(arr.length === 1) return false;
if(arr[0] === ")" || arr[0] === "]" || arr[0] === "}") return false;
arr.forEach((el) => {
if(el === "(" || el === "[" || el === "{") {
stack.push(el);
return;
}
if((el === ")" && stack[stack.length-1] === "(") ||
(el === "]" && stack[stack.length-1] === "[") ||
(el === "}" && stack[stack.length-1] === "{")) {
stack.pop();
} else {
answer = false;
}
});
if(stack.length !== 0) answer = false;
return answer;
};