Java Solution using 2 maps


  • 0
    S
    public class Solution {
        public String frequencySort(String s) {
            Map<Character, Integer> map = new HashMap<Character, Integer>();
            TreeMap<Integer, List<Character>> map2 = new TreeMap<>();
            
            for(int i=0;i<s.length();i++) {
                
                map.put(s.charAt(i),map.getOrDefault(s.charAt(i),0)+1);
            }
            
            for(Character ch:map.keySet()){
                int freq = map.get(ch);
                if(!map2.containsKey(freq)) map2.put(freq,new LinkedList<>());
                int j=0;
                map2.get(freq).add(ch);
            }
            
            List<Character> list = new LinkedList<>();
            StringBuilder sb = new StringBuilder();
            String str="";
            while(!map2.isEmpty()){
                Map.Entry<Integer,List<Character>> entry= map2.pollLastEntry();
                List<Character> list1 = entry.getValue();
                int j=0,k=0;
                while(j<list1.size()){
                    k=0;
                    while(k<entry.getKey()){
                    sb.append(list1.get(j));
                        k++;
                    }
                    //str+=list1.get(j);
                    j++;
                }
            }
            
            return sb.toString();
            
        }
    }
    

Log in to reply
 

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