Tuesday 24 June 2014

Balanced parenthesis check

Balanced parenthesis check for expression using javascript

Given an expression with series of braces,curly braces and big brackets " () {} [] ", you have to determine that whether these parenthesis are balanced or not. If given a string " ({}) ", by looking at it we can clearly say that parenthesis are balanced. Today we are going to implement this using javascript. We will be using data structure stack.


/**
* Stack that will hold the braces
*/
var stack = [];

/**
* Returns "Correct" when parenthesis are validated, "Incorrect" otherwise
*/
function validString(input1)
{ 
   if(processExp(input1))
    return "Correct";
   else
    return "Incorrect";
} 

function processExp(exp)
{
   for(var i =0;i<exp.length;i++)
   {
      if(exp[i] == '(' || exp[i] == '{' || exp[i] == '[')
        stack.push(exp[i]);
      else if(exp[i] == ')' || exp[i] == '}' || exp[i] == ']')
      {
        if(stack.length==0 || !isMatchingPair(stack[stack.length-1],exp[i]))
           return false;
        else
           stack.pop();
      }
   }
   if(stack.length==0)
      return true;
   else
      return false;
}

function isMatchingPair(ch1,ch2)
{
   if(ch1 == '(' && ch2 == ')')
     return true;
   else if(ch1 == '{' && ch2 == '}')
     return true;
   else if(ch1 == '[' && ch2 == ']')
     return true;
   else
     return false;
}


Call validString("([])") to check the expression. Hope you understood this simple program

1 comment: