Very Easy Java Solution!!!


  • 0
    S
    public String frequencySort(String s) {
         
            Map<Character, StringBuilder> hp = new HashMap<>();
            for(int i = 0; i< s.length(); i++){
                if(!hp.containsKey(s.charAt(i))){
                    hp.put(s.charAt(i), new StringBuilder().append(s.charAt(i)));
                }else{
                    hp.put(s.charAt(i), hp.get(s.charAt(i)).append(s.charAt(i)));
                }
            }
            List<StringBuilder> sb = new LinkedList<>(hp.values());
            Collections.sort(sb, new Comparator<StringBuilder>(){
                public int compare(StringBuilder a, StringBuilder b){
                    if(b.length() < a.length()){
                        return -1;
                    }
                    if(b.length() > a.length()){
                        return 1;
                    }
                    else{
                        return a.toString().compareTo(b.toString());
                    }
                }
            });
            StringBuilder res = new StringBuilder();
            for(StringBuilder ss : sb){
                res.append(ss);
            }
            
            return res.toString();
        }
    

Log in to reply
 

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