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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- How do you run Balanced Parentheses With Slice Stack?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.