Algorithm: It only needs one stack. We assume it receives the parenthesis one by one. For each received parenthesis, if

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: 899604
Joined: Mon Aug 02, 2021 8:13 am

Algorithm: It only needs one stack. We assume it receives the parenthesis one by one. For each received parenthesis, if

Post by answerhappygod »

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