Time Limited --Java


  • 0
    O

    public String frequencySort(String s){
    Map<Character,Integer> map=new HashMap<Character,Integer>();
    for(int i=0;i<s.length();i++){
    if(map.containsKey(s.charAt(i))){
    int count=map.get(s.charAt(i));
    count++;
    map.put(s.charAt(i), count);
    }else{
    map.put(s.charAt(i), 1);
    }
    }
    List<Map.Entry<Character,Integer>> list=new ArrayList<Map.Entry<Character,Integer>>();
    list.addAll(map.entrySet());
    Collections.sort(list,new Comparator<Map.Entry<Character,Integer>>(){
    public int compare(Map.Entry<Character,Integer> m,Map.Entry<Character,Integer> n){
    return n.getValue()-m.getValue();
    }
    });
    String result="";
    for(Iterator<Map.Entry<Character,Integer>> it=list.iterator();it.hasNext();){
    Map.Entry<Character, Integer> entry=it.next();
    for(int i=0;i<entry.getValue();i++){
    result=result+entry.getKey().toString();
    }
    }
    return result;
    }


Log in to reply
 

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