Turn String aaaabbbbddd into a4b4d3

java, string

Solution

Employ a `Map<Character, Integer>` instead. Attempt to insert the new character into the map; if it already exists, then increment the value for that particular character.

Example:

Map<Character, Integer> countMap = new HashMap<>();
if(!countMap.containsKey('a')) {
    countMap.put('a', 1);
} else {
    countMap.put('a', countMap.get('a') + 1);
}

Problem

I'm trying to get a head start on practicing interview questions and I came across this one: Turn String aaaabbbbddd into a4b4d3 You would basically want to convert the existing string into a string with each unique character occurrence and the number of times the character occurs. This is my solution but I think it could be refined into something more elegant: ``` String s = "aaaabbbbddd"; String modified = ""; int len = s.length(); char[] c = s.toCharArray(); int count = 0; for (int i = 0; i < len; i++) { count = 1; for (int j = i + 1; j < len; j++) { if (c[i] == ' ') { break; } if (c[i] == c[j]) { count++; c[j] = ' '; } } if (c[i] != ' ') { modified += c[i] + "" + count; } } System.out.println(modified); ``` Does anyone have any other suggestions for a solution?

Original source