-5

I have a String and I need to count occurances of successive characters of the string.

String s1="aabbcccaaa";

It should print output as

a2b2c3a3

String s1="aabbcccaaa";

char c[]=s1.toCharArray();
StringBuffer sb=new StringBuffer();

LinkedHashMap<Character,Integer> map=new LinkedHashMap<Character,Integer>();




for(int i=0;i<c.length;i++)
{
    Character c1=c[i];
    Integer frequency=map.get(c1);
    map.put(c1, (frequency==null)?1:frequency+1);

    if(map.size()>1 && c[i]!=c[i-1])
    {
        sb.append(c[i-1]+""+map.get(c[i-1]));
        map.remove(c[i-1]);
    }



}
sb.append(map);
System.out.println(sb);
Vivek S
  • 53
  • 2
  • 8

1 Answers1

1

I am not sure how i can achieve counts if same elements occur again.

Hint #1: Test the current character against the previous one.

Hint #2: Ask yourself, why do you need to use a Map?

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216