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.
Example 1: Input: s = “()” Output: true
Example 2: Input: s = “()[]{}” Output: true
Example 3: Input: s = “(]” Output: false
Constraints: 1 <= s.length <= 104 s consists of parentheses only ‘()[]{}’.
/** * @param {string} s * @return {boolean} */ var isValid = function(s) { let stack = []; for (let i = 0; i < s.length; i++) { if (s[i] === '(' || s[i] === '[' || s[i] === '{') { stack.push(s[i]); } if (s[i] === ')') { if (stack.length === 0 || stack.pop() != '(') returnfalse; } if (s[i] === ']') { if (stack.length === 0 || stack.pop() != '[') returnfalse; } if (s[i] === '}') { if (stack.length === 0 || stack.pop() != '{') returnfalse; } } return stack.length === 0 ? true : false; };
相关题目
1 2 3 4 5 6 7 8 9
20. Valid Parentheses 678. Valid Parenthesis String 921. Minimum Add to Make Parentheses Valid 1111. Maximum Nesting Depth of Two Valid Parentheses Strings 1003. Check If Word Is Valid After Substitutions 1249. Minimum Remove to Make Valid Parentheses 1541. Minimum Insertions to Balance a Parentheses String 1963. Minimum Number of Swaps to Make the String Balanced 2116. Check if a Parentheses String Can Be Valid