I already solved this one from CodingBat, but I'm unsatisfied with my solution and I feel I could have made it much shorter. Most of the other recursion tasks could be solved by a one line conditional for the base case and a one line return statement usually using ternary operator. So, could I have made this any shorter or more readable?
Given a string, compute recursively the number of times lowercase "hi" appears in the string, however do not count "hi" that have an 'x' immedately before them.
public int countHi2(String str) {
if (str.length() <= 1) {
return 0;
}
if (str.startsWith("x") && str.charAt(1) != 'x') {
return countHi2(str.substring(2));
}
else if (str.startsWith("hi")) {
return 1 + countHi2(str.substring(2));
}
else {
return countHi2(str.substring(1));
}
}