10 lines Java8 Solution


  • 0
    F
    public class Solution {
        public String frequencySort(String s) {
            if (s == null) return s;
            Map<Character, Integer> counter = new HashMap<>((int) (s.length() / 0.75));
            for (char c: s.toCharArray()) {
                if (counter.containsKey(c)) counter.put(c, counter.get(c) + 1);
                else counter.put(c, 1);
            }
            List<Map.Entry<Character, Integer>> result = counter.entrySet().stream().sorted((k1, k2) -> k2.getValue().compareTo(k1.getValue())).collect(Collectors.toList());
            StringBuffer sb = new StringBuffer();
            result.forEach(res -> {for (int c = res.getValue(); c > 0; c--) {sb.append(res.getKey());}});
            return sb.toString();
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.