Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a substring from a string, repeatedly

Problem: Remove the substring t from a string s, repeatedly and print the number of steps involved to do the same.

Explanation/Working:

For 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.

So, here's what I have tried:

  1. Code 1:

    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;
    }
    

    I am just able to pass 9/14 test cases on Hackerrank, due to some reason (I am getting "Wrong Answer" for rest of the cases). After a while, I found out that there is something called replace() method in Java. So, I tried using that by replacing the if condition and came up with a second version of code.

  2. Code 2:

    static int maxMoves(String s, String t) {
        int count = 0,i;
    
        while(true)
        {
            if(s.contains(t))
                s.replace(t,""); //Marked Statement
            else break;
    
            ++count;
        }
    
        return count;
    }
    

    But for some reason (I don't know why), the "Marked Statement" in the above code gets executed infinitely (this I noticed when I replaced the "Marked Statement" with System.out.println(s.replace(t,""));). I don't the reason for the same.

Since, I am passing only 9/14 test cases, there must be some logical error that is leading to a "Wrong Answer". How do I overcome that if I use Code 1? And if I use Code 2, how do I avoid infinite execution of the "Marked Statement"? Or is there anyone who would like to suggest me a Code 3?

Thank you in advance :)

like image 870
Prakhar Saxena Avatar asked Apr 12 '26 21:04

Prakhar Saxena


1 Answers

Try saving the new (returned) string instead of ignoring it.

s = s.replace(t,"");

replace returns a new string; you seemed to think that it alters the given string in-place.

like image 103
Prune Avatar answered Apr 14 '26 12:04

Prune



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!