Post my solution beat 89%


  • 0
    X
    public class Solution {
        class Object {
            char c;
            int cnt;
            Object(char c, int cnt) {
                this.c = c;
                this.cnt = cnt;
            }
        }
        public String frequencySort(String s) {
            char[] chars = s.toCharArray();
            Object[] objs = new Object[128];
            for (int i = 0; i < chars.length; i++) {
                if (objs[chars[i]] == null) {
                    objs[chars[i]] = new Object(chars[i], 1);
                } else {
                    objs[chars[i]].cnt += 1;
                }
            }
            Arrays.sort(objs, new Comparator<Object>() {
                public int compare(Object o1, Object o2) {
                    if (o1 == null && o2 == null) {
                        return 0;
                    }
                    if (o1 == null) {
                        return -1; 
                    }
                    if (o2 == null) {
                        return 1;
                    }
                    return o2.cnt - o1.cnt;
                }
            });
            StringBuilder sb = new StringBuilder();
            for (Object obj : objs) {
                if (obj == null) {
                    continue;
                }
                int count = obj.cnt;
                char ch = obj.c;
                while (count > 0) {
                    count--;
                    sb.append(ch);
                }
            }
            return sb.toString();
        }
    }
    

    My idea is build a new object with char and count of its occurance, and sort with them. The intuition is pretty naive.


Log in to reply
 

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