Page 1 of 1

Extra Credit (10 pts): Previously, you were asked to design an algorithm to detects a sequence of parentheses is balance

Posted: Fri May 20, 2022 4:41 pm
by answerhappygod
Extra Credit (10 pts): Previously, you were
asked to design an algorithm to detects a sequence of parentheses
is balanced or not using stack. Below is the algorithm. Please
write a Java program to implement the algorithm. Please be as much
syntactically correct as possible.
Algorithm: It only needs one stack. We assume
it receives the parenthesis one by one. For each received
parenthesis, if it is left, push into the stack. If it is right,
check the stack: if the stack is empty, it is unbalanced
(as in this subsequence, it has more right parentheses than
left, which is unbalanced) and returns; if the stack is
not empty, pop the top left parenthesis (as it matches with the
incoming right parenthesis), and move to the next parenthesis in
the sequence.
Repeat above process. When there are no more parentheses
received, check the stack. If it is empty, it is balanced;
otherwise, it is unbalanced (as there are more left
parentheses than right parentheses).