Hints for Practice Recursion Questions
2) It might be helpful if you wrote two helper methods:
- boolean
isDigit(char c)
- returns true if the character is a digit
- boolean
isOperator(char c)
- returns true if the character is an operator ( i.e. a '+' or '-' )
There are two base cases:
- the List is empty, in which case the result is false
- the List has one Character, in which case the result can be true or
false
You might find the methods charAt and substring defined by
the String
class to be useful.
3) An array a of length 0 or 1 is, by definition,
sorted.
The recursive call only has to happen if a[0] <= a[1];
otherwise the array is not sorted.
The method Arrays.copyOfRange
might be useful for the recursive call.
4) The basic idea is to recursively check the input string from left to
right. I can think of at least three ways to solve this problem:
- Use two recursive methods. The first method recursively checks strings
that begin the character 'a'; if the
string begins with 'a', the method
recursively checks the remainder of the string (i.e. it checks the new
string that is the original string with the first character removed). Note
that the new string might be valid if it begins with an 'a' or "bb". Your first
method works for the case where the new string starts with an 'a'. You can
create a second method that recursively checks strings that begin with
"bb".
- Use one recursive method that has two parameters:
- The string to check.
- The string that was removed by the previous method call (i.e ""
if this is the first time the method has been called; "a" or "bb"
otherwise).
By passing in the string that was previously removed you can figure out
what the next recursive call must be.
- Use one recursive method that has one parameter:
- The string to check.
You have to be clever about how you create the new string to recursively
check.
You might find the methods charAt, substring, and startsWith defined by
the String
class to be useful.