Description
Valid Parentheses
EasyGiven 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
Example 4:
Input: s = "([])"
Output: true
Example 5:
Input: s = "([)]"
Output: false
Constraints:
1 <= s.length <= 104sconsists of parentheses only'()[]{}'.
Solutions
Straightforward, although better performance could have been achieved - not attempted due to low number of test cases.
Language: javascript()DONE
CPU Performance21.20%
x
Memory Performance12.20%
x
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const map = new Map([
['(', ')'],
['{', '}'],
['[', ']'],
]);
const stack = [];
for (const char of s) {
if (map.has(char)) {
stack.push(char);
} else if (stack.length > 0 && map.get(stack[stack.length - 1]) === char) {
stack.pop();
} else {
return false;
}
}
return stack.length === 0;
};