Hi I'm working on the implementation of a boolean method to check if an expression has balanced parentheses using recursion. I cant figure out how to check if two elements of a given expression match i.e ( ).
I was able to finish it without a problem using stacks, but recursion is giving me a really hard time since I dont know how to check for two matching pairs of parentheses.
Well this is what i have so far.
/**
* Checks if the expression is balanced or not, making use of recursion.
* @param in Expression to be checked.
*/
public static boolean recIsBalanced(String in)
{
if(in.isEmpty())
return true;
if(isOpen(in.charAt(0)))
{
return recIsBalanced(in.substring(1));
}
if(isClose(in.charAt(0)))
return recIsBalanced(in.substring(1));
else
return false;
}
//Static parameters to check whether the character is open or a close parentheses
static String open = "([{";
static String close = ")]}";
private static boolean isOpen(char ch)
{
return open.indexOf(ch) != -1;
}
private static boolean isClose(char ch)
{
return close.indexOf(ch) != -1;
}
private static boolean isMatching(char chOpen, char chClose)
{
return open.indexOf(chOpen) == close.indexOf(chClose);
}