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:

  1. Save the code in a file named parentheses_balancer.go.
  2. Open a terminal or command prompt.
  3. Navigate to the directory where the file is stored.
  4. 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.

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)