1
+ // The nested brackets problem is a problem that determines if a sequence of
2
+ // brackets are properly nested. A sequence of brackets s is considered properly nested
3
+ // if any of the following conditions are true:
4
+ // - s is empty
5
+ // - s has the form (U) or [U] or {U} where U is a properly nested string
6
+ // - s has the form VW where V and W are properly nested strings
7
+ // For example, the string "()()[()]" is properly nested but "[(()]" is not.
8
+ // The function called isBalanced takes as input a string which is a sequence of brackets and
9
+ // returns true if input is nested and false otherwise.
10
+
11
+ package main
12
+
13
+ import (
14
+ "bufio"
15
+ "fmt"
16
+ "os"
17
+ "strings"
18
+ )
19
+
20
+ func isBalanced (input string ) string {
21
+
22
+ if len (input ) > 0 {
23
+ var stack []byte
24
+ for i := 0 ; i < len (input ); i ++ {
25
+ if input [i ] == '(' || input [i ] == '{' || input [i ] == '[' {
26
+ stack = append (stack , input [i ])
27
+ } else {
28
+ if len (stack ) > 0 {
29
+ pair := string (stack [len (stack )- 1 ]) + string (input [i ])
30
+ stack = stack [:len (stack )- 1 ]
31
+
32
+ if pair != "[]" && pair != "{}" && pair != "()" {
33
+ return input + " is not balanced."
34
+ }
35
+ } else {
36
+ return input + " is not balanced."
37
+ }
38
+ }
39
+ }
40
+ if len (stack ) == 0 {
41
+ return input + " is balanced."
42
+ }
43
+ }
44
+ return "Please enter a sequence of brackets."
45
+ }
46
+
47
+ func main () {
48
+ reader := bufio .NewReader (os .Stdin )
49
+ fmt .Print ("Enter sequence of brackets: " )
50
+ text , _ := reader .ReadString ('\n' )
51
+
52
+ text = strings .TrimSpace (text )
53
+ fmt .Println (isBalanced (text ))
54
+ }
0 commit comments