Turn String aaaabbbbffffd into a4b4d3

前端 未结 5 1540
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 04:46

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

5条回答
  •  长情又很酷
    2021-01-05 05:23

    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 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 entry: map.entrySet()) {
                System.out.print(entry.getKey() + "" + entry.getValue());
            }
        }
    }
    

    Output with TreeMap: a4b4d3

    Output with HashMap: d3b4a4

提交回复
热议问题