SHARE
TWEET

Untitled

a guest Sep 11th, 2019 84 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. public class SortCharactersByFrequency {
  2.     public static void main(String[] args) {
  3.         System.out.println(frequencySort("Leetcode"));
  4.     }
  5.  
  6.     public static String frequencySort(String s) {
  7.         HashMap<Character, Integer> map = new HashMap<>();
  8.         for (int i = 0; i < s.length(); i++) {
  9.             map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
  10.         }
  11.         PriorityQueue<CharacterFrequency> priorityQueue = new PriorityQueue<>();
  12.         for (HashMap.Entry<java.lang.Character, Integer> entry : map.entrySet()) {
  13.             priorityQueue.offer(new CharacterFrequency(entry.getKey(), entry.getValue()));
  14.         }
  15.         StringBuilder stringBuilder = new StringBuilder();
  16.         while (!priorityQueue.isEmpty()) {
  17.             CharacterFrequency characterFrequency = priorityQueue.poll();
  18.             for (int i = 0; i < characterFrequency.frequency; i++) {
  19.                 stringBuilder.append(characterFrequency.character);
  20.             }
  21.         }
  22.         return stringBuilder.toString();
  23.     }
  24.     static class CharacterFrequency implements Comparable<CharacterFrequency> {
  25.  
  26.         Character character;
  27.         int frequency;
  28.  
  29.         public CharacterFrequency(java.lang.Character character, int frequency) {
  30.             this.character = character;
  31.             this.frequency = frequency;
  32.         }
  33.  
  34.         @Override
  35.         public int compareTo(CharacterFrequency that) {
  36.             if (this.frequency > 0 || that.frequency > 0) {
  37.                 return that.frequency - this.frequency;
  38.             }
  39.             return that.character.compareTo(this.character);
  40.         }
  41.     }
  42. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top