Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active August 29, 2015 14:14
Show Gist options
  • Save dgodfrey206/869f514c6ddcc20db1cf to your computer and use it in GitHub Desktop.
Save dgodfrey206/869f514c6ddcc20db1cf to your computer and use it in GitHub Desktop.
Java recursion #4
/* 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