Nested parentheses matching

When we are solving mathematical expressions, the first thing we need to consider is the correctness of nested parentheses. If the parentheses are not nested properly, then calculation might not be possible, or may be wrong. Let us look at some examples:

From the preceding expressions, only the first one is correct; the other two are incorrect, as the parentheses are not nested properly. In order to identify whether or not the parentheses are nested, we can use stack to implement the solution. Here is the pseudo algorithm for the implementation:

valid = true 
s = empty stack
for (each character of the string) {
if(character = ( or { or [ )
s.push(character)
else if (character = ) or } or ] ) {
if(s is empty)
valid = false

last = s.pop()
if(last is not opening parentheses of character)
valid = false
}
}
if(s is not empty)
valid = false

If we look at the pseudocode, it looks very simple. The goal is to ignore any numbers, operands, or empty spaces from the string and only consider the parentheses, curly braces, and brackets. If they are opening brackets, we will push into the stack. If they are closing brackets, we are going to pop the stack. If the popped parenthesis is not the opening one we are trying to match, then it is not valid. At the end of the loop, the stack should be empty if the string is valid. But if the stack is not empty, then there are extra parentheses, so the string is not valid. Now let us convert this to a program:

function expressionChecker(string $expression): bool { 
$valid = TRUE;
$stack = new SplStack();

for ($i = 0; $i < strlen($expression); $i++) {
$char = substr($expression, $i, 1);

switch ($char) {
case '(':
case '{':
case '[':
$stack->push($char);
break;

case ')':
case '}':
case ']':
if ($stack->isEmpty()) {
$valid = FALSE;
} else {
$last = $stack->pop();
if (($char == ")" && $last != "(")
|| ($char == "}" && $last != "{")
|| ($char == "]" && $last != "[")) {

$valid = FALSE;
}
}
break;
}

if (!$valid)
break;
}

if (!$stack->isEmpty()) {
$valid = FALSE;
}

return $valid;
}

Now let us run the three examples we discussed earlier:

$expressions = []; 
$expressions[] = "8 * (9 -2) + { (4 * 5) / ( 2 * 2) }";
$expressions[] = "5 * 8 * 9 / ( 3 * 2 ) )";
$expressions[] = "[{ (2 * 7) + ( 15 - 3) ]";

foreach ($expressions as $expression) {
$valid = expressionChecker($expression);

if ($valid) {
echo "Expression is valid ";
} else {
echo "Expression is not valid ";
}
}

This will produce the following output, which is exactly what we wanted:

Expression is valid
Expression is not valid
Expression is not valid
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset