Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
- 題目大意
判斷一個包含括號的字符串是否匹配,包括3種括號('(','[','{')
維護一個棧,遇到左括號就壓入棧,遇到右括號就把棧頂的彈出看是否匹配。
注意最后要檢查棧是否為空。
/**
* @param {string} s
* @return {boolean}
*/
const isValid = function (s) {
const stack = [];
const leftSet = new Set(['(', '[', '{']);
const rightSet = new Set([')', ']', '}']);
const pair = {
')': '(',
']': '[',
'}': '{',
};
for (let i = 0; i < s.length; i++) {
const char = s[i];
if (leftSet.has(char)) {
stack.push(char);
}
if (rightSet.has(char)) {
if (stack.pop() !== pair[char]) {
return false;
}
}
}
return stack.length === 0;
};