I am going through the CodingBat exercises for Java. Here is the one I have just finished:
Given a string, compute recursively the number of times lowercase
hi
appears in the string, however do not counthi
that have anx
immedately before them.
And here is my code:
public int countHi2(String str) { if (str.length() < 3) { return str.equals("hi") ? 1 : 0; } if (str.substring(0, 3).equals("xhi")) { return countHi2(str.substring(2)); } if (str.substring(0, 2).equals("hi")) { return 1 + countHi2(str.substring(2)); } else { return countHi2(str.substring(1)); } }
This is the first in a recursion exercise which I have needed to change the base case to accommodate how the rest of the code works. I originally made it so that whenever an x
is reached, it returns a substring from 2
(because the following hi
is irrelevant), but of course, this is useless when there are two x
's adjacent to one another.
I am still getting used to the idea of recursion, so I would like to know if this is a 'good' solution or not. Can it be made more efficient?