Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

programming logic of java program

Tags:

java

logic

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;
                }
like image 407
user3867590 Avatar asked May 21 '26 06:05

user3867590


1 Answers

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.

like image 122
Elliott Frisch Avatar answered May 23 '26 19:05

Elliott Frisch



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!