Java solution with sort() and Map


  • 0
    H

    '''
    public class Solution {
    public static String frequencySort(String s) {

    	class Pair{
    		char c;
    		int n;
    		Pair(char c, int n){
    			this.c = c;
    			this.n = n;
    		}
    	}
        
        Map<Character,Integer> map = new HashMap<Character, Integer>();
        for(int i=0;i<s.length();i++){
        	char c = s.charAt(i);
        	if(!map.containsKey(c))
        		map.put(c, 1);
        	else
        		map.put(c, map.get(c)+1);
        }
        Pair[] data = new Pair[map.size()];
        int i=0;
        for(Character c : map.keySet())
        	data[i++]=new Pair(c,map.get(c));
        
        Arrays.sort(data,new Comparator<Pair>(){
        	public int compare(Pair o1, Pair o2){
        		return o2.n-o1.n;
        	}
        });
        StringBuilder sb = new StringBuilder();
        for(Pair p : data){
        	for(i=0;i<p.n;i++)
        		sb.append(p.c);
        }
        return sb.toString();
    }
    

    '''


Log in to reply
 

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