IsBalanced returns true if provided input string is properly nested. Input is a sequence of brackets: '(', ')', '[', ']', '{', '}'. A sequence of brackets `s` is considered properly nested if any of the following conditions are true: - `s` is empty; - `s` has the form (U) or [U] or {U} where U is
(input string)
| 21 | // space complexity: O(n) |
| 22 | |
| 23 | func IsBalanced(input string) bool { |
| 24 | if len(input) == 0 { |
| 25 | return true |
| 26 | } |
| 27 | |
| 28 | if len(input)%2 != 0 { |
| 29 | return false |
| 30 | } |
| 31 | |
| 32 | // Brackets such as '{', '[', '(' are valid UTF-8 characters, |
| 33 | // which means that only one byte is required to code them, |
| 34 | // so can be stored as bytes. |
| 35 | var stack []byte |
| 36 | |
| 37 | for i := 0; i < len(input); i++ { |
| 38 | if input[i] == '(' || input[i] == '{' || input[i] == '[' { |
| 39 | stack = append(stack, input[i]) |
| 40 | } else { |
| 41 | if len(stack) > 0 { |
| 42 | pair := string(stack[len(stack)-1]) + string(input[i]) |
| 43 | stack = stack[:len(stack)-1] |
| 44 | |
| 45 | if pair != "[]" && pair != "{}" && pair != "()" { |
| 46 | // This means that two types of brackets has |
| 47 | // been mixed together, for example "([)]", |
| 48 | // which makes seuqence invalid by definition. |
| 49 | return false |
| 50 | } |
| 51 | } else { |
| 52 | // This means that closing bracket is encountered |
| 53 | // before opening one, which makes all sequence |
| 54 | // invalid by definition. |
| 55 | return false |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | // If sequence is properly nested, all elements in stack |
| 61 | // has been paired with closing elements. If even one |
| 62 | // element has not been paired with a closing bracket, |
| 63 | // means that sequence is invalid by definition. |
| 64 | return len(stack) == 0 |
| 65 | } |
no outgoing calls