Valid Parentheses
Last updated
Last updated
usage of opening and closing parenthesis follows last in first out (LIFO), the last opening parenthesis must follow with the first corresponding closing parenthesis.
- create a map that has a [opening parenthesis, closing parenthesis], key-value pair
- create an empty array as a stack
- loop through the string
- if character is an opening parenthesis
- push corresponding closing parenthesis into stack
- if character is a closing parenthesis
- pop last element from stack and compare if it is the right pair
- if it's not, return false immediately
- when the loop completes and
- if the stack is empty, return true
- else, return falsevar isValid = function (s) {
const closingTagsMap = {
"(": ")",
"{": "}",
"[": "]",
};
let stack = [];
let len = s.length;
if (len % 2 !== 0) {
return false;
}
for (let i = 0; i < len; i++) {
if (closingTagsMap[s[i]]) {
stack.push(s[i]);
} else {
if (s[i] !== closingTagsMap[stack.pop()]) {
return false;
}
}
}
return !stack.length;
};