Last active
August 29, 2015 14:14
-
-
Save dgodfrey206/869f514c6ddcc20db1cf to your computer and use it in GitHub Desktop.
Java recursion #4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Given a string and a non-empty substring sub, compute recursively | |
the number of times that sub appears in the string, without the sub | |
strings overlapping. */ | |
public int strCount(String str, String sub) { | |
if (str.length() < sub.length()) return 0; | |
if (str.substring(0, sub.length()).equals(sub) && | |
!str.substring(sub.length(), sub.length()).equals(sub)) | |
{ | |
return 1 + strCount(str.substring(sub.length()), sub); | |
} | |
return strCount(str.substring(1), sub); | |
} | |
/* | |
Given a string and a non-empty substring sub, compute recursively | |
if at least n copies of sub appear in the string somewhere, possibly | |
with overlapping. N will be non-negative. */ | |
public boolean strCopies(String str, String sub, int n) { | |
if (n == 0) | |
return true; | |
if (str.length() < sub.length()) | |
return false; | |
if (str.substring(0, sub.length()).equals(sub)) | |
return strCopies(str.substring(1), sub, n - 1); | |
return strCopies(str.substring(1), sub, n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment