I\'m trying to get a head start on practicing interview questions and I came across this one:
Turn String aaaabbbbffffd into a4b4d3
You would basically want t
To add on to @Makoto's wonderful answer, in your situation, I would use a TreeMap
instead of a HashMap
. A TreeMap
will allow you to print in alphabetical order. I have also added the print code to show you how it would look. It's fully runnable.
import java.util.Map;
import java.util.TreeMap;
public class MapPractice {
public static void main(String[] args) {
Map<Character, Integer> map = new TreeMap<>();
String blah = "aaaabbbbffffd";
for (int i = 0; i < blah.length(); i++) {
char c = blah.charAt(i);
if (!map.containsKey(c)) {
map.put(c, 1);
} else {
map.put(c, (map.get(c) + 1));
}
}
for (Map.Entry<Character, Integer> entry: map.entrySet()) {
System.out.print(entry.getKey() + "" + entry.getValue());
}
}
}
Output with TreeMap
: a4b4d3
Output with HashMap
: d3b4a4
Here is the code that I tried.
I think you can't ask for a simpler code than this.
String s = "aaaabbbbffffd", modified = "";
int len = s.length(), i = 0, j = i + 1, count = 1;
char[] c = s.toCharArray();
for (; i < len; i = j) {
count = 1;
for (; j < len; j++)
if (c[i] == c[j])
count++;
else {
j++;
break;
}
modified += c[i] + "" + count;
}
System.out.println(modified);
Here is my solution
public String countChars(String in){
LinkedHashMapMap<Character, Integer> map = new LinkedHashMap<Character, Integer>();
for(char c: in.toCharArray()){
Integer count = map.get(c);
if(count==null){
count=0;
}
count++;
map.put(c,count);
}
String out ="";
for(Entry<Character, Integer> e : map.entrySet()){
out += e.getKey()+e.getValue();
}
return out;
}
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);
}
My version
StringBuilder sb = new StringBuilder();
int count = 0;
char last = s.charAt(0);
for(char c : s.toCharArray()) {
if (c == last) {
count++;
} else {
sb.append(last).append(count);
count = 0;
last = c;
}
}
if (count != 0) {
sb.append(last).append(count);
}
System.out.println(sb);