Valid Parentheses
Description
Given a string 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.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
Solution(javascript)
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const map = {
')': '(',
']': '[',
'}': '{'
};
s = s.split('');
let t = [];
while(s.length) {
if (!map[s[0]]) {
t.push(s[0]);
s.splice(0, 1)
} else if (t.length && t[t.length - 1] === map[s[0]]) {
t.splice(t.length - 1, 1);
s.splice(0, 1);
} else {
return false;
}
}
if(t.length) return false;
return true;
};