Trying to "compress" a string by replacing duplicate characters with numbers (For example, the string aabcccccaaa
would become a2blc5a3
). I tried to use a Linked HashMap to solve the problem because the input order needs to be preserved, but the counter I created doesn't seem to be incrementing properly. Any insight would be greatly appreciated.
public class StringCompression {
public static void main(String[] args) {
String s = "aabcccccaaa";
System.out.println(compString(s));
}
public static String compString(String str) {
LinkedHashMap <Character, Integer> alphabet = new LinkedHashMap<>();
StringBuilder strbdr = new StringBuilder();
for(int i = 0; i < str.length(); i++) {
if(alphabet.containsKey(str.charAt(i))) {
alphabet.put(str.charAt(i), alphabet.get(str.charAt(i))+1);
}
alphabet.put(str.charAt(i), 1);
}
// System.out.println(alphabet.entrySet());
for(var entry : alphabet.entrySet()) {
strbdr.append(entry.getKey());
strbdr.append(entry.getValue());
}
return strbdr.toString();
}
}