Problem: Remove the substring t
from a string s
, repeatedly and print the number of steps involved to do the same.
Example: t = ab
, s = aabb
. In the first step, we check if t
is contained within s
. Here, t is contained in the middle i.e. a(ab)b
. So, we will remove it and the resultant will be ab
and increment the count value by 1
. We again check if t
is contained within s
. Now, t
is equal to s
i.e. (ab)
. So, we remove that from s
and increment the count. So, since t
is no more contained in s
, we stop and print the count value, which is 2
in this case.
I tried to solve this using recursion
static int maxMoves(String s, String t) {
if ( null == s || "" == s || null == t || "" == t){
return 0;
}
int i = s.indexOf(t);
if(i != -1) {
return maxMoves(s.substring(0, i)+ s.substring(i+t.length(), s.length()), t) + 1;
} else {
return 0;
}
}
But I am only passing 9/14 test cases. I also tried this,
static int maxMoves(String s, String t) {
int count = 0,i;
while(true)
{
if(s.contains(t))
{
i = s.indexOf(t);
s = s.substring(0,i) + s.substring(i + t.length());
}
else break;
++count;
}
return count;
}
But that also only passed 9/14 cases.
Could anyone help me figure out which cases I am not covering?