Created
October 3, 2021 13:20
-
-
Save pilosus/864265e010e0296accef349e9bd6f427 to your computer and use it in GitHub Desktop.
Check if a string contains balanced parenthesis in Clojure
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
| (def openning ["(" "[" "{"]) | |
| (def closing [")" "]" "}"]) | |
| (def parens (zipmap openning closing)) | |
| (defn parens-balanced? | |
| [s] | |
| (loop [input-string s | |
| stack []] | |
| (if (empty? input-string) | |
| (empty? stack) | |
| (let [character (str (first input-string)) | |
| rest-str (apply str (rest input-string))] | |
| (cond | |
| (some #(= character %) openning) | |
| (recur rest-str (conj stack (get parens character))) | |
| (some #(= character %) closing) | |
| (if (or (empty? stack) (not= (last stack) character)) | |
| false | |
| (recur rest-str (pop stack))) | |
| :else (recur rest-str stack)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment