Last active
December 23, 2015 12:59
-
-
Save latompa/6639528 to your computer and use it in GitHub Desktop.
solution_177
http://www.4clojure.com/problem/177
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
; solution to http://www.4clojure.com/problem/177 | |
(defn balanced? | |
[x] | |
(let [tokens (vec (clojure.string/replace x #"[^\(\)\[\]\{\}]" "")) | |
brackets { \{ \} \( \) \[ \]} | |
starting-bracket? (fn [x] (brackets x)) | |
matching-bracket? (fn [a b] (= (brackets a) b))] | |
(loop [stack '() | |
[curr & more] tokens] | |
(if (nil? curr) | |
(empty? stack) | |
(recur (if (or (starting-bracket? curr) | |
(not (matching-bracket? (first stack) curr))) | |
(conj stack curr) | |
(rest stack)) | |
more))))) | |
; tests | |
(balanced? "())") | |
false | |
(balanced? "([]([(()){()}(()(()))(([[]]({}()))())]((((()()))))))") | |
true | |
(balanced? "([]([(()){()}(()(()))(([[]]({}([)))())]((((()()))))))") | |
false | |
(balanced? "[") | |
false | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment