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, otherwisefalse
. - 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