Efficient Parenthesis Checker
Sunday, July 23rd, 2006Here is a simple example of checking that a given equation has correctly matched parenthesis. It could be expanded to multiple types of parenthesis, but this version simply shows for ( ) type.
Examples:
- ()), ((), ()(())) would not be accepted
- (((()))), ()()(()()), ()(())() would be
public boolean check_parenthesis(char equation[])
{
int i, unmatched=0;
for(i=0; i < equation.length; i++)
{
if(equation[i]==')')
{
unmatched--;
if(unmatched < 0)
return false;
}
else if(equation[i]=='(')
{
unmatched++;
}
}
return (unmatched==0);
}