Valid Parentheses
Problem
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.
Example 1:
Input: s = "()" Output: true
Example 2:
Input: s = "()[]{}"
Output: true
Example 3:
Input: s = "(]" Output: false
Constraints:
1 <= s.length <= 104sconsists of parentheses only'()[]{}'.
Solution
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const stack = [];
const pairs = {
"(" : ")",
"{" : "}",
"[" : "]"
}
for (const i of s) {
if (i in pairs) {
stack.push(i);
} else if (j = stack.pop()) {
if (pairs[j] !== i) {
return false
}
} else {
return false;
}
}
return !stack.length
};
Verify if the given string s is valid by storing the left brackets in a stack stack and popping the top to test if it matches the corresponding right bracket.