// L-13 MCS 360 Wed 22 Sep 2010 : match_brackets

/* We show how to use a stack to test whether the parentheses
   in an expression match. */

#include <iostream>
#include <string>
#include <stack>

using namespace std;

int main()
{
   string expression;

   cout << "give an expression : ";
   getline(cin,expression,'\n');
   cout << "checking " << "\"" << expression << "\""
        << " for balanced parentheses" << endl;

   stack<char> brackets;
   string opening_brackets = "({[";
   string closing_brackets = ")}]";

   bool balanced = true;

   for(int i=0; i<expression.size(); i++)
      if(opening_brackets.find(expression[i]) != string::npos)
      {
         brackets.push(expression[i]);
         cout << "pushed " << expression[i] << endl;
      }
      else if(closing_brackets.find(expression[i]) != string::npos)
      {
         int k = closing_brackets.find(expression[i]);
         if(brackets.empty())
         {
            balanced = false;
            break;
         }
         else
         {
            char c = brackets.top();
            if(c != opening_brackets[k])
            {
               cout << "unbalanced parenthesis : "
                    << c << " != " << expression[i] << endl;
               balanced = false;
               break;
            }
            else
            {
               cout << expression[i] << " matches " << c << endl;
               brackets.pop();
               cout << "popped " << c << endl;
            }
         }
      }
   cout << "parenthesis in \"" << expression;
   if(balanced && brackets.empty())
      cout << "\" are balanced" << endl;
   else
      cout << "\" are not balanced" << endl;

   return 0;
}

