Bucket sort with HashMap


  • 0
    F
    public class Solution {
        public String frequencySort(String s) {
            Map<Character,StringBuilder> map=new HashMap<Character,StringBuilder>();
            int len=s.length();
            for(int i=0;i<len;i++)
            {
                char c=s.charAt(i);
                map.put(c,map.getOrDefault(c,new StringBuilder()).append(c));
            }
            StringBuilder bucket[]=new StringBuilder[len+1];
            for(char c:map.keySet())
            {
                int f=map.get(c).length();
                if(bucket[f]==null)
                    bucket[f]=new StringBuilder();
                bucket[f].append(map.get(c));
            }
            StringBuilder res=new StringBuilder();
            for(int i=len;i>0;i--)
                if(bucket[i]!=null)
                    res.append(bucket[i]);
            return res.toString();
        }
    }
    

Log in to reply
 

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