Answer to Question #240344 in C for xyz

Question #240344

Two brackets are considered to be a matched pair if an opening bracket (i.e., (, [, or { ) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of brackets are not matched. 


Write a program to determine whether the input sequence of brackets is balanced or not. If a string is balanced, it prints YES on a new line; otherwise, print NO on a new line. 

Example: 

Input: {[()]} and Output: YES

Input: {[(])} and Output: NO



1
Expert's answer
2021-09-23T17:48:18-0400
#include <iostream>
#include <stack>

bool is_balanced(const std::string& pattern) {
    std::stack<char> stack;
    for (size_t i = 0; i < pattern.size(); i = i + 1) {
        switch (pattern[i]) {
            case '(': case '[': case '{':
                stack.push(pattern[i]);
                break;
            case ')':
                if (!stack.empty() and stack.top() == '(')
                    stack.pop();
                break;
            case ']':
                if (!stack.empty() and stack.top() == '[')
                    stack.pop();
                break;
            case '}':
                if (!stack.empty() and stack.top() == '{')
                    stack.pop();
                break;
        }
    }
    return stack.empty();
}

int main() {
    while (true) {
        std::cout << "Enter new string sequence: ";
        std::string pattern;
        if (pattern == "quit") return 0;
        std::cin >> pattern;
        if (is_balanced(pattern)) {
            std::cout << "YES" << std::endl;
        } else {
            std::cout << "NO" << std::endl;
        }
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS