DEV Community

Discussion on: Daily Challenge #51 - Valid Curly Braces

Collapse
 
tiash990 profile image
Tiash • Edited

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