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.
#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;
}