Valid Parentheses
Problem statement
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: trueExample 3:
Input: s = "(]"Output: false
Constraints:
1 <= s.length <= 104sconsists of parentheses only'()[]{}'.
My solution
/**
* @param {string} s
* @return {boolean}
*/
var isValid = function(s) {
const front = new Set(["(", "{", "["])
const back = new Map([[")", "("], ["}", "{"], ["]", "["]])
const stack = [];
for (const char of s.split("")) {
// console.log("char", char)
if (front.has(char)) {
stack.push(char)
} else {
const last = stack.pop();
// console.log("last", last)
if (back.get(char) !== last) {
return false
}
}
}
return stack.length === 0
};