Share my java solution with PriorityQueue beats 97%


  • 0
    C
    public String frequencySort(String s) {
        PriorityQueue<int[]> pq = new PriorityQueue<>(52, new Comparator<int[]>() {
        	public int compare(int[] o1, int[] o2) {
        		return o2[1] - o1[1];
        	}
    	});
        int[] hash = new int[128];
        for(char c : s.toCharArray()){
        	hash[c]++;
        }
        for (int i = 0; i < hash.length; i++) {
        	if (hash[i] != 0) {
    			int[] ele = new int[2];
    			ele[0] = i;
    			ele[1] = hash[i];
    			pq.add(ele);
    		}
    	}
        StringBuilder ret = new StringBuilder();
        while(!pq.isEmpty()){
        	int[] ele = pq.poll();
        	while((ele[1]--) != 0){
        		ret.append((char)ele[0]);
        	}
        }
        return ret.toString();
    }

Log in to reply
 

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