let is_balanced s = let stack = Stack.create () in let n = String.length s in let ok = ref true in let i = ref 0 in while !i < n && !ok do let c = s.[!i] in (if c = '(' || c = '[' || c = '{' then Stack.push c stack else if c = ')' then (if Stack.is_empty stack || Stack.pop stack <> '(' then ok := false) else if c = ']' then (if Stack.is_empty stack || Stack.pop stack <> '[' then ok := false) else if c = '}' then (if Stack.is_empty stack || Stack.pop stack <> '{' then ok := false)); i := !i + 1 done; !ok && Stack.is_empty stack ;; (if is_balanced "({[abc]d}e)" then 1 else 0) + (if is_balanced "(a]" then 1 else 0) + (if is_balanced "{[}]" then 1 else 0) + (if is_balanced "(())" then 1 else 0) + (if is_balanced "" then 1 else 0)