Java Concise and Easy to Read


  • 0
    class Node {
        char c;
        int count;
        public Node(char c, int count) {
            this.c = c;
            this.count = count;
        }
    }
    public class Solution {
        public String frequencySort(String s) {
            if (s == null || s.length() == 0) return s;
            Map<Character, Integer> map = new HashMap<>();
            for (char c : s.toCharArray()) {
                map.put(c, map.getOrDefault(c, 0) + 1);
            }
            PriorityQueue<Node> pq = new PriorityQueue<>(new Comparator<Node>(){
                public int compare(Node p, Node q) {
                    return q.count - p.count;
                }
            });
            for (char c : map.keySet()) {
                pq.offer(new Node(c, map.get(c)));
            }
            StringBuilder sb = new StringBuilder();
            while (!pq.isEmpty()) {
                Node node = pq.poll();
                while (node.count-- > 0) {
                    sb.append(node.c);
                }
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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