This C++ program checks if a string consisting of parentheses is balanced. A string of parentheses is considered balanced if every type of bracket (curly, square, round) is closed and opened properly.

Program Code

#include <iostream>
#include <stack>
#include <string>

bool isBalanced(const std::string& s) {
    std::stack<char> stk;
    for (char c : s) {
        switch (c) {
            case '(':
            case '{':
            case '[':
                stk.push(c);
                break;
            case ')':
                if (stk.empty() || stk.top() != '(') return false;
                stk.pop();
                break;
            case '}':
                if (stk.empty() || stk.top() != '{') return false;
                stk.pop();
                break;
            case ']':
                if (stk.empty() || stk.top() != '[') return false;
                stk.pop();
                break;
        }
    }
    return stk.empty();
}

int main() {
    std::string expression = "{[()]}";
    std::cout << "Expression: " << expression << std::endl;
    std::cout << "Is balanced: " << (isBalanced(expression) ? "Yes" : "No") << std::endl;
    return 0;
}

Function Documentation

bool isBalanced(const std::string& s)

  • Parameters: s – A string containing the parentheses to check.
  • Returns: true if the string is balanced, otherwise false.
  • Description: The function iterates through each character of the string. If it encounters an opening bracket, it pushes it onto a stack. For each closing bracket, it checks the stack: if the stack is empty or the top of the stack does not match the corresponding opening bracket, the string is unbalanced. If the stack is empty after processing the entire string, it is balanced.

Example Usage

    std::string expression = "{[()]}";
    bool result = isBalanced(expression);
    std::cout << "Expression: " << expression << std::endl;
    std::cout << "Is balanced: " << (result ? "Yes" : "No") << std::endl;
    // Output will be: Yes

 

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 :)