Check for Balanced Parentheses using Stack – Java Code

Write a java code to check for balanced parentheses using stack. Given an expression containing characters ‘{‘,’}’,'(‘,’)’,'[‘,’]’. We have to write a java code to check whether an input string has valid parentheses.

An input string is valid if:

Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.

Example –

i) {[]}) – Invalid
ii) {()}[] – Valid

Subscribe Our Tutorials

Get Latest Updates on Facebook

Check for balanced parentheses using stack

Check for balanced parentheses using stack

Algorithm to check for balanced parentheses

i) Traverse a string.
ii) If the current character is starting bracket ‘{‘, ‘(‘, ‘[‘ then push it in a stack.
iii) If the current character is closing bracket ‘}’, ‘)’, ‘]’ and the top of the stack is
starting bracket then pop from the stack.
iv) After complete traversal, if the stack is empty then it is balanced otherwise it is not balanced.

Java program to check for balanced parentheses using stack

We have discussed the algorithm to solve this problem. Let’s write a java code to check for balanced parentheses in a string using stack.

 

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.