Naive Java Solution


  • 0
    Y
    public class Solution {
        class word
        {
            char name;
            int frequency;
            public word(char name,int frequency)
            {
                this.name=name;
                this.frequency=frequency;
            }
            public char getname()
            {
                return this.name;
            }
            public int getfrequency()
            {
                return this.frequency;
            }
        }
       class mycomparator implements Comparator<word>
       {   
           public int compare(word w1,word w2)
           {
               return w2.getfrequency()-w1.getfrequency();
           }
       }
        public String frequencySort(String s) {
            Map<Character,Integer>map=new HashMap<>();
            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);
                }
            }
            List<word> list=new ArrayList<word>();
            for(Map.Entry<Character,Integer>entry: map.entrySet())
            {   
                word w=new word(entry.getKey(),entry.getValue());
                list.add(w);
            }
            Collections.sort(list,new mycomparator());
            StringBuilder sb = new StringBuilder();
            for(int i=0;i<list.size();i++)
            {
                int count=list.get(i).getfrequency();
                while(count!=0)
                {
                    sb.append(list.get(i).getname());
                    count--;
                }
            }
            return sb.toString();
        }
    

    }


Log in to reply
 

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