My Java solution which beats 95.17%, easy to understand


  • 0
    K
    public String frequencySort(String s) {
            if (s == null || s.length() == 0) {
                return s;
            }
            PriorityQueue<String> que = new PriorityQueue<>(new Comparator<String>(){
                @Override
                public int compare(String s1, String s2) {
                    return s2.length() - s1.length();
                }
            });
            char[] sc = s.toCharArray();
            Arrays.sort(sc);
            int i = 0, j = 0;
            char pivot = sc[0];
            s = String.valueOf(sc);
            for (char x : sc) {
                if (x == pivot) {
                    j++;
                    continue;
                }
                que.offer(s.substring(i, j));
                i = j;
                pivot = sc[j];
                j++;
            }
            que.offer(s.substring(i, j));
            StringBuilder sb = new StringBuilder();
            while (!que.isEmpty()) {
                sb.append(que.poll());
            }
            return sb.toString();
        }
    

Log in to reply
 

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