Algorithm: It only needs one stack. We assume it receives the parenthesis one by one. For each received parenthesis, if
Posted: Fri May 20, 2022 4:46 pm
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).
This has to be done in java
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).
This has to be done in java