Sanket and string problem 1.0

i have used string builder but sill the code is not working —

import java.util.*;
public class Main
{
public static void main(String args[])
{
Scanner cin = new Scanner(System.in);
int k = cin.nextInt();
String str1 = cin.nextLine();
StringBuilder str = new StringBuilder(str);
int counta = 0, countb =0;
for(int i = 0;i<str.capacity();i++)
{
if(str.charAt(i) == ‘a’)
{ counta++; }
else
{ countb++; }
} int count = 0;
char ch1 = ‘a’, ch2 = ‘b’;
if(counta>countb){
while(count<=k){
for(int i = 0;i<str.capacity();i++)
{
if(str.charAt(i) == ‘b’)
{
str.charAt(i) = ch1;
count++;
}
}
}
}else
{
while(count<=k)
{
for(int i = 0;i<str.capacity();i++)
{
if(str.charAt(i) == ‘a’)
{
str.charAt(i) = ch2; count++;
}
}
}
}
System.out.println(str);
}
}

Hey @AbhishekAhlawat1102,
https://ide.codingblocks.com/s/147470 I have corrected your code for errors. You needn’t use while loop before for loop. Also, str.setCharAt(position, char) is the correct function. So, kindly compare your previous code and this code for better understanding. Also, this is incomplete and it will not give you the correct answer.

A better approach will be:

Take l and r to mark left and right index of the string under inspection. Start from l=0, r=0, count=0, max = -1.

Start with r<length of string. Increment the count whenever you find a different character than the one you are using to build a string (example: if we are forming a string of an only, then b is a different char).

While count is greater than k, decrement the count by one if the element at i index is different.

Increment i.

Then, compare max with count for maximum value.

And finally, increment r.

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.