This program checks if a string of parentheses is balanced. A balanced string means every opening parenthesis (‘(‘) has a corresponding closing parenthesis (‘)’) and they are correctly nested.
Program Code
package main
import (
"fmt"
)
// isBalanced checks if the given string of parentheses is balanced
func isBalanced(s string) bool {
var stack []rune
for _, char := range s {
switch char {
case '(':
stack = append(stack, char)
case ')':
if len(stack) == 0 {
return false // no matching opening parenthesis
}
stack = stack[:len(stack)-1] // pop the last element
default:
// Ignore other characters or handle errors if other characters are not allowed
return false
}
}
return len(stack) == 0 // if stack is empty, all parentheses are balanced
}
func main() {
testStrings := []string{"((()))", "(()", "())", "(())()"}
for _, str := range testStrings {
fmt.Printf("Is \"%s\" balanced? %v\n", str, isBalanced(str))
}
}
Explanation
- Function Definition: The function
isBalanced
takes a string and returns a boolean indicating whether the string’s parentheses are balanced. - Algorithm:
- Use a stack (implemented as a slice of runes) to keep track of opening parentheses.
- Iterate through each character in the string:
- If the character is an opening parenthesis, push it onto the stack.
- If it’s a closing parenthesis, check if the stack is empty. If it is, the string is not balanced because there’s no matching opening parenthesis. If not, pop the top of the stack.
- After processing all characters, the stack should be empty if the parentheses are balanced. If any opening parentheses remain in the stack, then there are unmatched opening parentheses, making the string unbalanced.
Running the Program
To execute this Go program:
- Save the code in a file named
parentheses_balancer.go
. - Open a terminal or command prompt.
- Navigate to the directory where the file is stored.
- Run the program by typing
go run parentheses_balancer.go
.
The output will display whether each string in the testStrings
slice is balanced or not. This example provides a straightforward approach to determine the balance of parentheses using a stack, which can be easily extended to include other types of brackets and braces if required.