Last active
September 5, 2023 03:24
-
-
Save Maximization/b1f045be9da26c4a7b8d2a4346930be5 to your computer and use it in GitHub Desktop.
Solution to the Valid Parentheses challenge from LeetCode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Author: Maxim Orlov <[email protected]> | |
* 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