Java solution | Easy to understand for beginners


  • 0
    V

    class letter implements Comparable<letter>
    {
    char ch;
    int f;
    public letter(char ch,int f)
    {
    this.ch = ch;
    this.f = f;
    }

    @Override
    public int compareTo(letter o) {
        return o.f - this.f;
    }
    

    }

    public class Solution {
    public String frequencySort(String s) {
    String res = "";
    if(s==null || s.length()==0)
    return res;

        HashMap<Character,letter> map = new HashMap<>();
        char[] arr = s.toCharArray();
        for(char ch : arr)
        {
            if(!map.containsKey(ch))
            {
                map.put(ch,new letter(ch,1));
            }
            else {
                letter temp = map.get(ch);
                map.put(ch, new letter(ch, temp.f + 1));
            }
        }
        PriorityQueue<letter> pq = new PriorityQueue<>();
        for(Map.Entry<Character,letter> entry : map.entrySet())
        {
            pq.add(entry.getValue());
            //System.out.println(entry.getKey() + "==" + entry.getValue().f);
        }
        StringBuilder sb = new StringBuilder();
        while(!pq.isEmpty())
        {
            letter temp = pq.poll();
            while(temp.f>0){
            sb.append(temp.ch);
            temp.f--;
            }
        }
        return sb.toString();
    }
    

    }


Log in to reply
 

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