Java solution


  • 0
    D
    public class Solution {
        public String frequencySort(String s) {
            if (s == null || s.length() == 0) {
                return "";
            }
            Map<Character, HelpObj> freqm = new HashMap<>();
            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);
                if (!freqm.containsKey(ch)) {
                    freqm.put(ch, new HelpObj(ch));
                }
                freqm.get(ch).freq++;
            }
            List<HelpObj> list = new ArrayList<>(freqm.values());
            Collections.sort(list, new Comparator<HelpObj>() {
                @Override
                public int compare(HelpObj o1, HelpObj o2) {
                    return o2.freq - o1.freq;
                }
            });
            StringBuffer sb = new StringBuffer();
            for (HelpObj obj : list) {
                for (int i = 0; i < obj.freq; i++) {
                    sb.append(obj.ch);
                }
            }
            return sb.toString();
        }
        
        class HelpObj {
            char ch;
            int freq;
            public HelpObj(char ch) {
                this.ch = ch;
            }
        }
    }
    

Log in to reply
 

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