Clean JAVA code using Heap


  • 0
    A
    public String frequencySort(String s) {
    	Map<Character, Node> map = new HashMap<Character, Node>();
    	for (char ch : s.toCharArray()) {
    		if (!map.containsKey(ch))
    			map.put(ch, new Node(ch, 1));
    		else {
    			Node node = map.get(ch);
    			node.count++;
    		}
    	}
    	
    	PriorityQueue<Node> pq = new PriorityQueue<Node>(1, (n1, n2) -> n2.count - n1.count);
    	for (char ch : map.keySet())
    		pq.add(map.get(ch));
    	
    	StringBuffer bf = new StringBuffer();
    	while (!pq.isEmpty()) {
    		Node n = pq.poll();
    		while (n.count-- > 0)
    			bf.append(n.ch);
    	}
    	return bf.toString();
    }
    
    class Node {
    	char ch;
    	int count;
    	public Node(char ch, int count) {
    		this.ch = ch;
    		this.count = count;
    	}
    }

Log in to reply
 

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