Answer to Question #235780 in C++ for Bill

Question #235780
Complete the body of this function. You do not need to check the precondition. You
may use the stack template class
bool balanced(const char p[ ], size_t n)
// Precondition: p[0]...p[n-1] contains n characters, each of which
// is '(', ')', '{' or '}'.
// Postcondition: The function returns true if the characters form a
// sequence of correctly balanced parentheses with each '(' matching
// a ')' and each '{' matching a '}'. Note that a sequence such as
// ( { ) } is NOT balanced because when we draw lines to match the
// parentheses to their partners, the lines cross each other. On the
// other hand, ( { } ) and { ( ) } are both balanced.
1
Expert's answer
2021-09-10T23:52:13-0400
#include <bits/stdc++.h>
using namespace std;
bool Balanced(string size_t)
{   
    stack<char> p;
    char n;
    for (int i = 0; i < size_t.length(); i++)
    {
        if (size_t[i] == '(' || size_t[i] == '['
            || size_t[i] == '{')
        {
            p.push(size_t[i]);
            continue;
        }
        if (p.empty())
            return false;
 
        switch (size_t[i]) {
        case ')':
            n = p.top();
            p.pop();
            if (n == '{' || n == '[')
                return false;
            break;
 
        case '}':
            n = p.top();
            p.pop();
            if (n == '(' || n == '[')
                return false;
            break;
 
        case ']':
            n = p.top();
            p.pop();
            if (n == '(' || n == '{')
                return false;
            break;
        }
    }
    return (p.empty());
}
int main()
{
    string size_t = "( { ) }";
    if (Balanced(size_t))
        cout << "Balanced";
    else
        cout << "UnBalanced";
    return 0;
}

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