Last active
July 13, 2024 20:05
-
-
Save DataKinds/e536fc6a11af6400c5a57c24e50efcfb to your computer and use it in GitHub Desktop.
Leetcode 20 (https://leetcode.com/problems/valid-parentheses/description/) in J
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
NB. here's a validator that only works with parens | |
NB. call it with c d '())()()()()()()())))))(())()(()' | |
d=: +/\@(=&'(' + -@=&')') NB. paren nesting depth | |
c=: {{ */ (0&= {: y),(=&0 +/ <&0 y) }} NB. nesting depth validator | |
NB. here's a validator that works with all the paren types given | |
NB. by the spec at https://leetcode.com/problems/valid-parentheses/description/ | |
NB. call it with isvalid '[()]{(()[]{})}' | |
identify=: (3&| ,. (<&3)) @ ('({[)}]'&i.) NB. returns (paren type, 0=open/1=close) | |
pop=: ((] {{throw. 'mismatched bracket'}})`(] }:)@.(= {:)) NB. x=paren type ({. @ identify), y=stack | |
push=: ,~ NB. x=paren type ({. @ identify), y=stack | |
stackit=: {{ ({.x) (pop`push)@.({:x) y }} NB. x=output of identify, y=stack | |
isvalid=: monad define | |
try. | |
a: -: {: (>a:) < F:. ((] identify)~ stackit ]) y | |
catcht. | |
0 return. | |
end. | |
) | |
isvalid '[()]{(()[]{})}' | |
isvalid '(]' | |
isvalid '[[[[))))' | |
isvalid '[(])' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment