Sha256: 2a75391cce0a4b0113825fd1c9d5ef3a1cb0d0693e8b191843b46015fd0a4da9

Contents?: true

Size: 1.35 KB

Versions: 122

Compression:

Stored size: 1.35 KB

Contents

package brackets

type bracketKind int

const (
	kindParen  bracketKind = iota
	kindSquare bracketKind = iota
	kindBrace  bracketKind = iota
	kindOther  bracketKind = iota
)

// Whether a bracket is an opening or closing bracket
type bracketForm bool

const (
	formOpen  bracketForm = true
	formClose bracketForm = false
)

type charInfo struct {
	kind bracketKind
	form bracketForm
}

// Bracket returns whether all the brackets in the input string are
// correctly nested.
func Bracket(input string) (bool, error) {
	var stack []bracketKind
	for _, char := range input {
		ci := info(char)
		if ci.kind == kindOther {
			continue
		}
		if ci.form == formOpen {
			stack = append(stack, ci.kind)
		} else {
			if len(stack) == 0 {
				return false, nil
			} else if stack[len(stack)-1] == ci.kind {
				stack = stack[:len(stack)-1]
			} else {
				return false, nil
			}
		}
	}
	return len(stack) == 0, nil
}

func info(char rune) charInfo {
	switch char {
	case '(':
		return charInfo{kind: kindParen, form: formOpen}
	case '[':
		return charInfo{kind: kindSquare, form: formOpen}
	case '{':
		return charInfo{kind: kindBrace, form: formOpen}
	case ')':
		return charInfo{kind: kindParen, form: formClose}
	case ']':
		return charInfo{kind: kindSquare, form: formClose}
	case '}':
		return charInfo{kind: kindBrace, form: formClose}
	default:
		return charInfo{kind: kindOther}
	}
}

Version data entries

122 entries across 122 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.179 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.178 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.177 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.176 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.175 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.174 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.173 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.172 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.171 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.170 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.169 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.167 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.166 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.165 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.164 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.163 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.162 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.161 tracks/go/exercises/bracket-push/example.go
trackler-2.2.1.160 tracks/go/exercises/bracket-push/example.go