Created
November 22, 2023 14:49
-
-
Save optimistiks/342729fc660637101839bcea8b6dc3ed to your computer and use it in GitHub Desktop.
Given a string that may consist of opening and closing parentheses, your task is to check whether or not the string contains valid parenthesization.
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
| function isValid(s) { | |
| const stack = []; | |
| const open = ["(", "[", "{"]; | |
| const closing = [")", "]", "}"]; | |
| for (const char of s) { | |
| const index = closing.indexOf(char); | |
| if (index !== -1 && stack[stack.length - 1] === open[index]) { | |
| stack.pop(); | |
| } else { | |
| stack.push(char); | |
| } | |
| } | |
| return stack.length === 0; | |
| } | |
| export { | |
| isValid | |
| }; | |
| // tc: O(n) | |
| // sc: O(n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment