Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ;; The purpose of the function is to match all unmatched parentheses in a given string
- ;; ") (()(" ===> "() (()())"
- ;; The function will loop through a given string one character at a time.
- ;; The count of (currently) unmatched left parentheses will be increased by one for each "(" found.
- ;; For each ")" found, two things might happen:
- ;; If there's currently any unmatched lefties, decrease the count of unmatched left parentheses by 1
- ;; (since we've found a matched pair)
- ;; Otherwise, if there's no unmatched "(", increase the count of unmatched right parenthesis by 1
- ;; (since the found ")" has no preceding partner)
- ;; Finally, add the appropriate amount of left and right parenthesis on each side of the string
- ;; so that every parenthesis has a matching partner in the returned result
- (defn match-parantheses [the-string]
- (loop [index 0
- unmatched-left 0
- unmatched-right 0]
- (if (< index (count the-string))
- (let [char (get the-string index)]
- (cond
- (= \( char) (recur (inc index) (inc unmatched-left) unmatched-right)
- (= \) char) (if (= unmatched-left 0)
- (recur (inc index) unmatched-left (inc unmatched-right))
- (recur (inc index) (dec unmatched-left) unmatched-right))
- :else (recur (inc index) unmatched-left unmatched-right)))
- (str
- (apply str (repeat unmatched-right "( "))
- the-string
- (apply str (repeat unmatched-left ") "))))))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement