I want to check if a String has matching braces, brackets or parenthesis.
For example:
{}
()
[]
I can do it with a stack. I want to do it with recursion. I was reading the answers for a similar question and the replies were recursion mixed in with a stack. An user responded to those answers saying that recursion is also a stack so your recursive method should not have a stack in the parameters — this makes sense to me.
I have a big problem though, I’m looking through the String backwards and always removing the last position I check until the String is empty so I return true. I can’t picture how I will check for the particular parts, braces, brackets or parenthesis without having an extra parameter in my method to hold what I am looking for. Yet I keep thinking there has to be an easier way to do this.
public boolean isBalanced(String in)
{
if(in.isEmpty())
return true;
if(in.charAt(in.length()) == '}')
{
return recIsBalanced(in.substring(0, in.length()));
}
else if(in.charAt(in.length()) == ']')
{
}
return recIsBalanced(in.substring(0, in.length()));
}
Easiest way to solve this problem using recursion is to shrink the string from both directions. You iterate from left and from right until you see . If these do not match, String is not balanced otherwise apply same algorithm for the String enclosed between those braces. Going only from one end will be a lot trickier and you will have to store some state.
EDIT: thanks to DanielFischer. Actually iterate from one side e.g. left until you find a brace(if this brace is not opening one return
false). Than iterate from the other side(in this case right) until you find a matching brace. Now the string will be balanced if and only if the substring enclosed within this braces is balanced and the string to the right of the closing bracket are both balanced using recursion.