Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.javascript
An input string is valid if:java
Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.數組
Example 1:app
Input: "()" Output: true Example 2:ide
Input: "()[]{}" Output: true Example 3:code
Input: "(]" Output: false Example 4:blog
Input: "([)]" Output: false Example 5:ip
Input: "{[]}" Output: true字符串
1.使用棧方法(使用數組的push()和pop()來模擬)input
var isValid = function(s) { let valid = true const stack = [] const mapper = { '{': '}', '(': ')', '[': ']' } if (s === '') { return valid; } for (let value of s) { let v = value; if (['{', '(', '['].indexOf(v) != -1) { stack.push(v) } else { if (stack.length == 0) { valid = false; } else { const va = stack.pop() if (mapper[va] != v) { valid = false; } } } } return valid; }