Java Concise Node implements Comparable


  • 0

    O(nlogn) due to sort

    public class Solution {
        class Node implements Comparable<Node> {
            char val;
            int count;
            public Node(char c, int count) {
                this.val = c;
                this.count = count;
            }
            public int compareTo(Node other) {
                return other.count - this.count;
            }
            
        }
        public String frequencySort(String s) {
            if (s == null || s.length() == 0) return "";
            int[] counting = new int[256];
            for (char c : s.toCharArray()) {
                counting[c]++;
            }
            List<Node> list = new ArrayList<>();
            for (int i = 0; i < 256; i++) {
                if (counting[i] > 0) list.add(new Node((char)i, counting[i]));
            }
            StringBuilder sb = new StringBuilder();
            Collections.sort(list);
            for (Node node : list) {
                for (int i = 0; i < node.count; i++) {
                    sb.append(node.val);
                }
            }
            return sb.toString();
        }
    }
    

Log in to reply
 

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