Here is my code for the method, does not give me errors but is not working when calling it out, any help would be appreciated thanks:
static boolean isBalanced(String expr){
Stack stack = new Stack();
for (char ch : expr.toCharArray()) {
if (ch == '{' || ch == '(' || ch == '[') {
stack.push(expr);
} else {
if (expr.isEmpty()) {
return false;
}
char latestOpenedPar = (char)stack.pop();
if (latestOpenedPar == '{' && ch != '}') {
return false;
} else if (latestOpenedPar == '(' && ch != ')') {
return false;
} else if (latestOpenedPar == '[' && ch != ']') {
return false;
}
}
}
return stack.isEmpty();
}
CodePudding user response:
If the string is "(abc)"
you are going to push the (
and then pop it four times, once for each of a
, b
, c
, and )
, which of course will not work. Also expr.isEmpty()
will never return true inside the loop because if it were empty, expr.toCharArray()
would have returned a zero-length array and the loop would execute zero times. Use peek()
to look at the top of the stack without removing it.
Also, your stack should be declared as:
Stack<Character> stack = new Stack<>();
in which case you would not need to cast the value returned by pop()
or peek()
; it would be automatically unboxed from a Character
to a char
.
CodePudding user response:
It is not very clear from the question but I guess you want to understand if the different brackets are "consistent".
if (expr.isEmpty()) {return false;}
this is useless because if the condition were true it would never enter the for loopif (ch == '{' || ch == '(' || ch == '[') {stack.push(expr);}
here you put in the stack the entire string taken as input but after you comparingstack.pop()
with the various brackets, so the right statement can bestack.push(ch);
- You do
stack.pop()
without checking that the stack has at least one element