Given a string
s
containing just the characters'('
,')'
,'{'
,'}'
,'['
and']'
, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: false
s
consists of parentheses only '()[]{}'
.var isValid = function(s) {
let stack = [];
const map = {
'(' : ')',
'{' : '}',
'[' : ']'
};
for (let i = 0 ; i < s.length; i++) {
if (s[i] === '(' || s[i] === '{' || s[i] === "[") {
stack.push(s[i]);
} else {
if (map[stack[stack.length - 1]] === s[i]) {
stack.pop();
} else return false;
}
}
return stack.length === 0;
};
자료구조 공부를 하며 비슷한 문제를 풀어봐서 접근하기 수월했다. 괄호 끼리의 짝이 있고 순서가 중요하기 때문에 stack을 통해 쉽게 풀 수 있는 문제였다. 괄호끼리의 짝을 map 객체에 넣어 논 후 여는 괄호이면 스택에 push하고 닫는 괄호라면 괄호에 맞는 짝인지를 map 객체에서 불러와 비교하고 최종적으로 스택의 length가 0이라면 true를 아니라면 false를 return하였다.