Java short solution but TLE


  • 0
    X
    public class Solution {
        public String frequencySort(String s) {
            Map<Character, String> map = new HashMap<>();
            for (int i = 0; i < s.length(); i++){
                char c = s.charAt(i);
                if (!map.containsKey(c)){
                    map.put(c, "" + c);
                } else {
                    map.put(c, map.get(c) + c);
                }
            }
            
            Queue<String> pq = new PriorityQueue<>((a, b) -> b.length() - a.length());
            for (String str : map.values()){
                pq.offer(str);
            }
            
            String res = "";
            while (!pq.isEmpty()){
                res += pq.poll();
            }
            return res;
        }
    }
    

Log in to reply
 

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