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.
strCopies("catcowcat", "cat", 2) → true
strCopies("catcowcat", "cow", 2) → false
strCopies("catcowcat", "cow", 1) → true
solution:
public boolean strCopies(String str, String sub, int n) {
return (copies(str,sub,0)==n);
}
int copies(String str,String sub, int index)
{
if(index>=str.length()-sub.length()+1)
{
return 0;
}
if(equals(str,sub,index,0))
{
return 1+ copies(str,sub,index+1);
}
return copies(str,sub,index+1);
}
boolean equals(String str,String sub,int strIndex,int subIndex)
{
if(subIndex==sub.length())
{
return true;
}
if(strIndex == str.length())
{
return false;
}
return str.charAt(strIndex)==sub.charAt(subIndex) && equals(str,sub,strIndex+1,subIndex+1);
}
No comments:
Post a Comment