Java Solution use Collections.sort

  • 0
    public class Solution {
        public String frequencySort(String s) {
            if(s.length()==0||s.length()==1||s.length()==2)return s;
            Map<Character,Integer> map = new HashMap<Character,Integer>();
            for(int i=0;i<s.length();i++){
                int t = map.getOrDefault(s.charAt(i),0);
            List<Map.Entry<Character,Integer>> list = new ArrayList<Map.Entry<Character,Integer>>(map.entrySet());
            Collections.sort(list,new Comparator<Map.Entry<Character,Integer>>(){
                public int compare(Map.Entry<Character,Integer> o1,Map.Entry<Character,Integer> o2){
                    if(o2.getValue()-o1.getValue()>0)return 1;
                    else if(o2.getValue()-o1.getValue()==0)return 0;
                    else return -1;
            StringBuilder sb = new StringBuilder();
            for(int i=0;i<list.size();i++){
                Map.Entry<Character,Integer> o1 = list.get(i);
                for(int j=0;j<o1.getValue();j++)
            return new String(sb);

Log in to reply

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