Balanced Parentheses With Slice Stack

A slice used as a stack matches every closer against the top opener; leftovers at the end or a mismatched pop both mean the sequence is broken.

GoData Integrity

Code

gosnippet
28 lines
package main

import "fmt"

// pairs: closing bracket -> the opening bracket it requires
var pairs = map[byte]byte{')': '(', ']': '[', '}': '{'}

func balanced(s string) bool {
	stack := make([]byte, 0, len(s))
	for i := 0; i < len(s); i++ {
		switch ch := s[i]; ch {
		case '(', '[', '{':
			stack = append(stack, ch)
		case ')', ']', '}':
			if len(stack) == 0 || stack[len(stack)-1] != pairs[ch] {
				return false
			}
			stack = stack[:len(stack)-1]
		}
	}
	return len(stack) == 0
}

func main() {
	for _, s := range []string{"{[()]}", "([)]", "(((", ")"} {
		fmt.Println(s, "->", balanced(s))
	}
}

Tracing the logic

Balanced Parentheses With Slice Stack comes down to the functions balanced and main.

The cycling part of this snippet is for i := 0; i < len(s); i++.

What to watch for

  • No package installation, no environment variables, no setup steps.

Using it

The entry-point signature is func balanced(s string) bool

Treat main as the orchestrator calling balanced in a fixed order.

Key statements

stack := make([]byte, 0, len(s))
stack = append(stack, ch)
return len(stack) == 0

Interactive Tools for This Topic

FAQ

How do you run Balanced Parentheses With Slice Stack?
Just run the file; everything it needs ships with the runtime itself.