Is the code correct? Two test cases are not working link: https://ide.codingblocks.com/s/158066
Sanket and Strings
Hi @rohit267
Your to test cases are failing because because your are solving the question considering that max length will be formed with that character only whose count is greater but this approach don’t work for all cases. For example : 1 baabaabbb . for this input your code shows output as 6 as it changes one of the a to b then it counts all the number of b’s but you have to compute the length of same characters. But the correct answer should be 5 replacing the b at 4th position.
Instead of this approach you should use the following approach :
- We check for maximum length of sub-string that can be formed by a and b.
- For doing this we traverse whole string and whenever we find a different character, we increase the count.
- If count becomes greater than k (at right index), we again start from 0th index and if we found different character we will decrease the count.
- When count will be equal to k (at left index) then at that point the length will be rightIndex-leftIndex+1.
- We repeat this process until we reach at the end of string and at that point we will return the maximum length.
- We do this for all characters and finally return the maximum length.
If still you are unable to get this approach i can provide you the code.
ok thanks, let me try once, I will get back to you.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.
Can you please explain me with code, cant understand properly, thanks in advance
Here is the code :