Problem:
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
Solution:
public int strCount(String str, String sub) { int strlen = str.length(); int sublen = sub.length(); if (strlen < sublen) return 0; if (str.substring(0,sublen).equals(sub)) return 1 + strCount(str.substring(sublen), sub); else return strCount(str.substring(1), sub); }
if (!str.contains(sub)) return 0;
ReplyDeleteelse return 1 + strCount(str.substring(str.indexOf(sub)+sub.length()), sub);
If we're going to use any old java.lang.string method, might as well defeat the purpose of this exercise entirely and not even bother with recursion:
DeleteString s=str.replace(sub,"");
return (str.length()-s.length())/sub.length();
public int strCount(String str, String sub) {
ReplyDeleteif(str.indexOf(sub)==-1) return 0;
if(str.indexOf(sub)!=-1)
{
return 1 + strCount(str.substring(str.indexOf(sub)+sub.length()), sub);
}
return 0;
}
if(str.equals("")) return 0;
ReplyDeleteif(str.startsWith(sub)) return 1 + strCount(str.substring(sub.length()), sub);
return strCount(str.substring(1), sub);
public int strCount(String str, String sub) {
ReplyDeleteif(str.isEmpty()){
return 0;
}
if(str.startsWith(sub)){
return 1 + strCount(str.substring(sub.length()), sub);
}
return strCount(str.substring(1), sub);
}
public int strCount(String str, String sub) {
ReplyDeleteif(str.isEmpty()){
return 0;
}
return (str.startsWith(sub))?
1 + strCount(str.substring(sub.length()), sub)
: strCount(str.substring(1), sub);
}