I am trying to create a program that takes a string as an argument into its constructor. I need a method that checks whether the string is a balanced parenthesized expression. It needs to handle ( { [ ] } ) each open needs to balance with its corresponding closing bracket. For example a user could input [({})] which would be balanced and }{ would be unbalanced. This doesn't need to handle letters or numbers. I need to use a stack to do this.
I was given this pseudocode but can not figure how to implement it in java. Any advice would be awesome.
Update- sorry forgot to post what i had so far. Its all messed up because at first i was trying to use char and then i tried an array.. im not exactly sure where to go.
import java.util.*;
public class Expression
{
Scanner in = new Scanner(System.in);
Stack<Integer> stack = new Stack<Integer>();
public boolean check()
{
System.out.println("Please enter your expression.");
String newExp = in.next();
String[] exp = new String[newExp];
for (int i = 0; i < size; i++)
{
char ch = exp.charAt(i);
if (ch == '(' || ch == '[' || ch == '{')
stack.push(i);
else if (ch == ')'|| ch == ']' || ch == '}')
{
//nothing to match with
if(stack.isEmpty())
{
return false;
}
else if(stack.pop() != ch)
{
return false;
}
}
}
if (stack.isEmpty())
{
return true;
}
else
{
return false;
}
}
}
The improved method, from @Smartoop.
Using node reference we can check easily
You are pushing
i
- the index - on the stack, and comparing againstch
. You should push and popch
.Here is the Code. I have tested all the possible test case on Hacker Rank.
static String isBalanced(String input) {
Similar to one of the code above in JAVA but It needs one more else statement added in order to avoid stack comparison with characters other than braces :
else if(bracketPair.containsValue(strExpression.charAt(i)))
This code works for all cases include other chars not only parentheses ex:
Please enter input
{ibrahim[k]}
true
()[]{}[][]
true saddsd] false