OCaml solution:
let rec balance (count, array) = let comb char = match char with | '{' -> 1 | '}' -> -1 | _ -> 0 in match array with | [] -> count = 0 | c :: cl -> if count < 0 then false else balance ((count + comb c), cl);; let explode str = let rec expl idx array = if idx < 0 then array else expl (idx - 1) (str.[idx] :: array) in expl (String.length str - 1) [];; let isBalanced string = balance (0, explode (string));;
Some outputs:
# isBalanced "";; - : bool = true # isBalanced "{";; - : bool = false # isBalanced "}";; - : bool = false # isBalanced "}{";; - : bool = false # isBalanced "{}";; - : bool = true # isBalanced "{}{}{}";; - : bool = true # isBalanced "{}{{{{{}{}}}}{}}";; - : bool = true # isBalanced "{}{{{{{}{}}}}{}";; - : bool = false
This solution skips the characters different from braces:
# isBalanced "abc";; - : bool = true # isBalanced "{abc}";; - : bool = true # isBalanced "{abc{}";; - : bool = false # isBalanced "{abc{a}}";; - : bool = true
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
OCaml solution:
Some outputs:
This solution skips the characters different from braces: