Reputation: 33
guys I'm having some problems with something really basic. I have a suggested solution to a problem that looks like (below) but I don't understand how the static argument of countX == str.substring(1) is supposed to search the entire String, the argument is a static 1 (?!?!) :
public int countX(String str) {
if (str.length() == 0) return 0;
if (str.charAt(0) == 'x') return 1 + countX(str.substring(1));
return countX(str.substring(1));
}
Instead I thought of this solution before looking up for the solution but can't figure out how to identify the right most char of the substring for comparison with the searched char 'x' (line : 3)
public int countX(String str) {
if (str.length()>0) {
if (str.charAt(str.substring(str.length()-1) == 'x'))
return countX (str.substring(str.length()-1)) + 1;
else
return countX (str.substring(str.length() -1)
}
else
return 0;
}
Any suggestion for my ignorance about the first solution and my mistake on the second ?Thanks in advance
Upvotes: 0
Views: 119
Reputation: 3608
Let me explain the first solution. The idea is to split the string into its first character and the rest.
To catch also the situation of an empty string, the length of the input is checked first. If length is 0, then the count of x is zero.
Upvotes: 1