題目: 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. Every close bracket has a corresponding open bracket of the same type.
var isValid = function (s) { const hashMap = { "(": ")", "{": "}", "[": "]" }; const stack = []; for (let ch of s) { if (hashMap[ch]) { // ch is an opening bracket stack.push(hashMap[ch]); } elseif (stack.length > 0 && stack[stack.length - 1] === ch) { //當空陣列裡面有值且陣列的最後一個值和 key 是一樣的就從陣列中刪除 // ch is a closing bracket and top of stack matches stack.pop(); } else { // ch is a closing bracket and top of the stack doesn't match returnfalse; } } return stack.length === 0; };
Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.