I want to test if an input String is balanced. It would be balanced if there is a matching opening and closing parenthesis, bracket or brace.
example:
{} balanced
() balanced
[] balanced
If S is balanced so is (S)
If S and T are balanced so is ST
public static boolean isBalanced(String in)
{
Stack st = new Stack();
for(char chr : in.toCharArray())
{
if(chr == '{')
st.push(chr);
}
return false;
}
I'm having problems choosing what to do. Should I put every opening or closing parenthesis, bracket, or brace in a stack then pop them out? If I pop them out, how does that really help me?
Following is a
Java
code sample to detect if a string is balanced.http://introcs.cs.princeton.edu/java/43stack/Parentheses.java.html
The idea is that -
( [ {
, push it on the stack.) ] }
, try to pop a matching opening brace( [ }
from stack. If you can't find a matching opening brace, then string is not balanced.Yes, a stack is a suitable choice for the task, or you could use a recursive function. If you use a stack, then the idea is you push each opening bracket on the stack, when you encounter a closing bracket you check that the top of the stack matches it. If it matches, pop it off, if not that is an error. When complete, the stack should be empty.
Well, roughly speaking, if it is balanced, that means your stack should be empty.
For that, you need to pop your stack when you parse a
}
Additional requirement is to check that
}
is preceded by{
or the character popped is a{
.Any feedback on this is most welcome. Please criticize if you find something is wrong or useless. I am just trying to learn.
1) For every opening bracket:
{ [ (
push it to the stack.2) For every closing bracket:
} ] )
pop from the stack and check whether the type of bracket matches. If not returnfalse
;i.e. current symbol in String is
}
and if poped from stack is anything else from{
then returnfalse
immediately.3) If end of line and stack is not empty, return
false
, otherwisetrue
.