Last active
May 1, 2024 21:14
-
-
Save zhaocnus/ec9a962f5d24c9cc6696524669691879 to your computer and use it in GitHub Desktop.
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
| /** | |
| * braces/brackets/parentheses validator | |
| */ | |
| function check(str) { | |
| const closers = { | |
| ')' : '(', | |
| '}' : '{', | |
| ']' : '[' | |
| }; | |
| const openers = { | |
| '(' : true, | |
| '{' : true, | |
| '[' : true | |
| }; | |
| const all = []; | |
| for (let i = 0; i < str.length; i++) { | |
| let char = str.charAt(i); | |
| if (closers[char]) { | |
| if (all.length === 0) return false; | |
| let opener = all[all.length - 1]; | |
| if (closers[char] === opener) { | |
| all.pop(); | |
| } | |
| } else if (openers[char]) { | |
| all.push(char); | |
| } | |
| } | |
| // Is valid if no outstanding opener | |
| return all.length === 0; | |
| } | |
| // test cases | |
| console.log(check('')); | |
| console.log(check('{ s[ dfg]fdgdfg ( ) }')); | |
| console.log(check('{ [ ( ] ) }')); | |
| console.log(check('{ [ }')); | |
| console.log(check('}')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment