Skip to content

Instantly share code, notes, and snippets.

@Maximization
Last active September 5, 2023 03:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Maximization/b1f045be9da26c4a7b8d2a4346930be5 to your computer and use it in GitHub Desktop.
Save Maximization/b1f045be9da26c4a7b8d2a4346930be5 to your computer and use it in GitHub Desktop.
Solution to the Valid Parentheses challenge from LeetCode
/**
* Author: Maxim Orlov <hello@maximorlov.com>
* Website: https://maximorlov.com
*
* @param {string} s
* @return {boolean}
*/
const OPEN_PARENS = ['(', '{', '['];
function isValid(s) {
const openedParens = [];
for (const char of s) {
if (!openedParens.length) {
if (!OPEN_PARENS.includes(char)) {
return false;
}
openedParens.push(char);
} else {
if (OPEN_PARENS.includes(char)) {
openedParens.push(char);
} else {
const openedParen = openedParens.at(-1);
if (openedParen === '(' && char !== ')') {
return false;
}
if (openedParen === '{' && char !== '}') {
return false;
}
if (openedParen === '[' && char !== ']') {
return false;
}
openedParens.pop();
}
}
}
return !openedParens.length;
};
console.log(isValid('()'))
console.log(isValid('()[]{}'))
console.log(isValid('(]'))
console.log(isValid('({{[)}})'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment