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

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

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

Post 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).
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply