aboutsummaryrefslogtreecommitdiff
path: root/leetcode/20-valid-parentheses/solution.rkt
blob: 559b90c1734f521250196d595b1a4526d82f34a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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 '()))