coding bat recursion :Given a string, return true if it is a nesting of zero or more pairs of parenthesis, like "(())" or "((()))". Suggestion: check the first and last chars, and then recur on what's inside them.
nestParen("(())") → true
nestParen("((()))") → true
nestParen("(((x))") → false
solution:
public boolean nestParen(String str)
{
return nest(str,0,str.length()-1);
}
public boolean nest(String str,int start,int end) {
if(start>end)
{
return true;
}
else if(str.charAt(start)=='(' && str.charAt(end)==')')
{
return nest(str,start+1,end-1);
}
else
{
return false;
}
}
No comments:
Post a Comment