mystery4
method
// note: overlapping matches count repeatedly
public static int countMatches(String str, String pattern)
{
if(str.length() < pattern.length())
return 0;
int matches = countMatches(str.substring(1), pattern);
if(str.substring(0, pattern.length()).equals(pattern))
matches++;
return matches;
}
The method counts the number of times p
/pattern
appears in str
.
The base case is if str
is shorter than p
/pattern
, in which case str
cannot contain p
/pattern
. This base case is important because the call to substring
assumes that str
is at least as long as p
/pattern
.
The conditional statement checks if the first p.length()
/pattern.length()
letters of str
are p
/pattern
. In other words, the conditional statement checks if str
starts with p
/pattern
. As with mystery1
/countOddDigits
, the method either adds 1 or does not depending on the condition, so it is counting.