Sunday, June 26, 2016


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




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+sub.length());
  }
 
  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)==str.charAt(subIndex) && equals(str,sub,strIndex+1,subIndex+1);
 
}

No comments:

Post a Comment