Java Solution Easy to Understand using Bucket Sort


  • 1
    S

    Inspired by 347. Top K Frequency Elements

    public class Solution {
    public String frequencySort(String s) {
        if (s == null || s.length() == 0) return "";
        
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        List<Character>[] bucket = new List[s.length() + 1];
        
        // Calculate character frequency
        for (Character c : s.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        
        // Fill bucket
        for (Character c : map.keySet()) {
            int freq = map.get(c);
            if (bucket[freq] == null) {
                bucket[freq] = new ArrayList<Character>();
            }
            bucket[freq].add(c);
        }
        
        // Build result
        StringBuilder sb = new StringBuilder();
        for (int i = bucket.length - 1; i > 0; i--) {
            if (bucket[i] != null) {
                for (Character c : bucket[i]) {
                    for (int j = 0; j < i; j++) {
                        sb.append(c);
                    }
                }
            }
        }
        
        return sb.toString();
    }
    

    }


Log in to reply
 

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