aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMistivia <i@mistivia.com>2024-01-30 08:12:35 +0800
committerMistivia <i@mistivia.com>2024-01-30 08:12:35 +0800
commit836d657d12dbb5a32a3780e4a056a3f46341d41f (patch)
treef30eb4a43d1d784305aad06c61ba28c6282a93f0
parent6bece4b15b4407ceb42cfff890262fd67e0a8409 (diff)
solve leetcode 20
-rw-r--r--leetcode/20-valid-parentheses/solution.rkt33
1 files changed, 33 insertions, 0 deletions
diff --git a/leetcode/20-valid-parentheses/solution.rkt b/leetcode/20-valid-parentheses/solution.rkt
new file mode 100644
index 0000000..559b90c
--- /dev/null
+++ b/leetcode/20-valid-parentheses/solution.rkt
@@ -0,0 +1,33 @@
+#lang racket
+
+;; https://leetcode.com/problems/valid-parentheses/
+
+(define (is-left-paren c)
+ (or (eq? c #\u28)
+ (eq? c #\[)
+ (eq? c #\{)))
+
+(define (right-paren c)
+ (cond ((eq? c #\u28) #\u29)
+ ((eq? c #\[) #\])
+ ((eq? c #\{) #\})))
+
+(define/contract (is-valid s)
+ (-> string? boolean?)
+ (define (loop s stack)
+ (if (= 0 (string-length s))
+ (null? stack)
+ (let ()
+ (define c (string-ref s 0))
+ (define remain (substring s 1))
+ (if (is-left-paren c)
+ (loop remain (cons c stack))
+ (if (null? stack)
+ #f
+ (let ()
+ (define stack-top (car stack))
+ (if (eq? c (right-paren stack-top))
+ (loop remain (cdr stack))
+ #f)))))))
+ (loop s '()))
+