exercism/go/bracket-push/bracket-push.go

26 lines
585 B
Go
Raw Normal View History

2016-08-13 23:20:14 +00:00
package bracket_push
// Bracket makes sure that all brackets match
func Bracket(s string) (bool, error) {
// Set up a map of matches that we care about
matches := make(map[byte]byte)
matches['}'] = '{'
matches[')'] = '('
matches[']'] = '['
var pairs []byte
for i := range s {
if v, ok := matches[s[i]]; ok {
// Found a match, it's a closing bracket
if len(pairs) == 0 || pairs[len(pairs)-1] != v {
return false, nil
}
pairs = pairs[:len(pairs)-1]
} else {
pairs = append(pairs, s[i])
}
}
if len(pairs) > 0 {
return false, nil
}
return true, nil
}