I need to create a program in java in which when the input given is say:
hhllyyjhhh
the output should be
h2l2y2j1h3
instead i get the output
h2l2y2j1
I know the reason why, but please tell me how should I correct it or may be tell a new logic.
in the following code T is the character array and ans is an empty string.
int counter=0;
for(int i=0;i<T.length;i++)
{
for(int j=i;j<T.length;j++)
{
if(T[i]==T[j])
{
counter++;
}
else
{
ans=ans+T[i]+counter;
i=j-1;
counter=0;
break;
}
The issue is you don't add the last character if your count matches all the way, I suggest you change your approach slightly and try and scan forward before you append the character and count (basically move your else outside the inner loop) -
char[] T = "hhllyyjhhh".toCharArray();
String ans = "";
for (int i = 0; i < T.length; i++) {
int count = 1;
while (i + count < T.length && T[i + count] == T[i]) {
count++;
}
ans += T[i] + String.valueOf(count);
i += count - 1;
}
System.out.println(ans);
Produces your requested output here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With