I have the below Problem Statement
PS: Given a string “str” 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.
Example are as shown below
strCopies("catcowcat", "cat", 2) → true
strCopies("catcowcat", "cow", 2) → false
strCopies("catcowcat", "cow", 1) → true
strCopies("iiijjj", "ii", 2) → true
I have written the code as shown below(without recursion) and is working fine for few test cases,except for others which are marked as FAIL.
:::Code is as shown below:::
public boolean strCopies(String str, String sub, int n) {
int len = sub.length();
int result=0;
if(len>0){
int start = str.indexOf(sub);
while(start !=-1){
result++;
start = str.indexOf(sub,start+len);
}
}
if(result==n){
return true;
}else return false;
}
Runs for above code as shown below(Marked in BOLD are FAILED TEST CASES)
Expected This Run
strCopies("catcowcat", "cat", 2) → true true OK
strCopies("catcowcat", "cow", 2) → false false OK
strCopies("catcowcat", "cow", 1) → true true OK
strCopies("iiijjj", "ii", 2) → true false FAIL
strCopies("iiiiij", "iii", 3) → true false FAIL
strCopies("ijiiiiij", "iiii", 2) → true false FAIL
Could you check and let me know what is wrong with the code for FAIL TEST CASES ?Im unable to consider the Overlapping scenarios.
Well, your first problem is that your method isn’t recursive. I suspect you want to work with
substringas well asindexOf…As for why your current method isn’t working, I suspect it’s because you’re using
start + leninstead ofstart + 1to find the next starting position. So when trying to find “ii” in “iii”, you should first look at position 0, then position 1 – currently you’re looking at position 2, which would mean it wouldn’t find the second “ii” starting at 1.