#include <iostream>
#include<stack>
using namespace std;
bool checkingBrackets(string expression)
{
stack<char> str;
char k;
for (int n = 0; n < expression.length(); n++)
{
if (expression[n] == '(' || expression[n] == '['
|| expression[n] == '{')
{
str.push(expression[n]);
continue;
}
if (str.empty())
return false;
switch (expression[n]) {
case ')':
k = str.top();
str.pop();
if (k == '{' || k == '[')
return false;
break;
case '}':
k = str.top();
str.pop();
if (k == '(' || k == '[')
return false;
break;
case ']':
k = str.top();
str.pop();
if (k == '(' || k == '{')
return false;
break;
}
}
return (str.empty());
}
// Testing code
int main()
{
string expression = "{()}[]";
if (checkingBrackets(expression))
cout << "Balanced";
else
cout << "Not Balanced";
return 0;
}
Comments
Leave a comment