Skip to content

Instantly share code, notes, and snippets.

@sbsatter
Created August 19, 2016 14:48
Show Gist options
  • Save sbsatter/ad1a5a34423d4e5e1f10963bcb9b5117 to your computer and use it in GitHub Desktop.
Save sbsatter/ad1a5a34423d4e5e1f10963bcb9b5117 to your computer and use it in GitHub Desktop.
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. strCount("catcowcat", "cat") → 2 strCount("catcowcat", "cow") → 1 strCount("catcowcat", "dog") → 0
public int strCount(String str, String sub) {
int index=str.indexOf(sub);
int l= sub.length();
if(index==-1){
return 0;
}
return 1+ strCount(str.substring(0,index)
+str.substring(index+l, str.length()), sub);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment