Search code examples
javastringlinkedhashmap

Linked Hash Map counter not properly incrementing


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();
    }
}

Solution

  • Problem 1

    The line alphabet.put(str.charAt(i), 1) keeps reseting each value to 1 , you need to put it in a else

    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);
        } else {
            alphabet.put(str.charAt(i), 1);
        }
    }
    

    Problem 2

    First fix leads to a5b1c5 as maps have unique keys, so you can't count the a at the beginning and the a at the end


    Just keep track of the previous char seen, and a counter

    public static String compString(String str) {
        StringBuilder sb = new StringBuilder();
        char prev = '\0';
        int count = 0;
        for (char letter : str.toCharArray()) {
            if (prev == '\0') {
                prev = letter;
            } else if (prev != letter) {
                sb.append(prev).append(count);
                count = 0;
                prev = letter;
            }
            count += 1;
        }
        return sb.append(prev).append(count).toString();
    }