Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading