using namespace std;
int func(string str)
{
if(str.length() == 0)
return 0;
else
{
if(str.at(0) == '(')
return 1 + func(str.substr(1,str.length()));
else if(str.at(0) == ')')
return -1 + func(str.substr(1,str.length()));
else
return func(str.substr(1,str.length()));
}
}
int main()
{
string str1 = "((()())(()())";
if(func(str1) == 0)
cout << "Balanced Parentheses" << endl;
else
cout << "Unbalanced Parentheses" << endl;
return 0;
}
A balanced set of parentheses would have each parentheses opened and then closed (potentially nested). For example the following sentences are balanced.
I told him (that it’s not (yet) done). (But he wasn’t listening)
(if (zero? x) max (/ 1 x))
The following 2 are not
:-)
())(