Problem:
Balanced Brackets
bool is_balanced(string expression) {
stack<char>brackets;
for(int i=0;i<expression.length();i++)
{
if(expression[i]=='(' || expression[i]=='{' || expression[i]=='[')
brackets.push(expression[i]);
else if(!brackets.empty())
{
if(expression[i]==')' && brackets.top()=='(')
brackets.pop();
else if(expression[i]=='}' && brackets.top()=='{')
brackets.pop();
else if(expression[i]==']' && brackets.top()=='[')
brackets.pop();
}
else return false;
}
if(brackets.empty()) return true;
return false;
}
No comments:
Post a Comment