Drill

ProblemsGo › patterns

Balanced delimiters

easypatternsStacksStringsGo

A config linter walks a snippet and rejects it if the brackets, braces and parentheses do not nest cleanly.

balancedDelimiters(text: string) → bool

Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

func balancedDelimiters(text string) bool {
	
}

Worked examples

CallResult
balancedDelimiters("()")true
balancedDelimiters("([])")true
balancedDelimiters("(]")false
balancedDelimiters("[(])")false

Hint

Push each opener, and when a closer arrives the top of the stack must be its matching opener.

Reference solution in Go
func balancedDelimiters(text string) bool {
	expect := []byte{}
	for i := 0; i < len(text); i++ {
	    ch := text[i]
	    if ch == '(' {
	        expect = append(expect, ')')
	    } else if ch == '[' {
	        expect = append(expect, ']')
	    } else if ch == '{' {
	        expect = append(expect, '}')
	    } else if ch == ')' || ch == ']' || ch == '}' {
	        if len(expect) == 0 || expect[len(expect)-1] != ch {
	            return false
	        }
	        expect = expect[:len(expect)-1]
	    }
	}
	return len(expect) == 0
}

The same problem in another language

More patterns problems in Go