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
If i want to know that a substring exists in a given string or not, always try to use indexOf keyword rather than '==' operator. Because
String is immutable. i.e. Strings cannot be altered. When you alter a string (by adding to it for example), you are actually creating a new string object.
WorstCase:
static int strCount(String str, String sub) {
int n = sub.length();
int len = str.length();
if(len < n) return 0;
String tmp = str.substring(0,n);
if(tmp.contains(sub)) // never use this in string (tmp == sub)
{
return strCount(str.substring(n, len), sub)+1;
}
else {
return strCount(str.substring(1,len), sub);
}
}
Better solution:
Use of 'indexOf ' string inbuild method:
static int strCount(String str, String sub)
{
return strCountUtil(str,sub,sub.length());
}
private static int strCountUtil(String str, String sub, int n)
{
int len = str.length();
if(len < n) return 0;
int index = str.indexOf(sub);
if(index >= 0)
{
return 1 + strCountUtil(str.substring(index+n), sub, n);
}
return 0;
}
private static int
"catdogccatca"
|
dogccatca
|
ca