Advertisement
1988coder

767. Reorganize String

Nov 21st, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.60 KB | None | 0 0
  1. /*
  2. Time Complexity: O(N log N)
  3. Space Complexity: O(N)
  4.  
  5. N = Length of the input string.
  6. */
  7. class Solution {
  8.     public String reorganizeString(String S) {
  9.         if (S == null || S.length() == 0) {
  10.             return "";
  11.         }
  12.         if (S.length() == 1) {
  13.             return S;
  14.         }
  15.        
  16.         Map<Character, Integer> countMap = new HashMap();
  17.         for (char c : S.toCharArray()) {
  18.             countMap.put(c, countMap.getOrDefault(c, 0)+1);
  19.         }
  20.        
  21.         PriorityQueue<Map.Entry<Character, Integer>> queue = new PriorityQueue<Map.Entry<Character, Integer>>(
  22.             (a,b) -> (a.getValue() != b.getValue() ? b.getValue() - a.getValue() : a.getKey() - b.getKey()));
  23.         queue.addAll(countMap.entrySet());
  24.        
  25.         StringBuilder sb = new StringBuilder();
  26.        
  27.         while (queue.size() >= 2) {
  28.             Map.Entry<Character, Integer> firstEntry = queue.poll();
  29.             Map.Entry<Character, Integer> secondEntry = queue.poll();
  30.             sb.append(firstEntry.getKey());
  31.             sb.append(secondEntry.getKey());
  32.             if (firstEntry.getValue() > 1) {
  33.                 firstEntry.setValue(firstEntry.getValue() - 1);
  34.                 queue.offer(firstEntry);
  35.             }
  36.             if (secondEntry.getValue() > 1) {
  37.                 secondEntry.setValue(secondEntry.getValue() - 1);
  38.                 queue.offer(secondEntry);
  39.             }
  40.         }
  41.        
  42.         if (queue.size() == 1) {
  43.             sb.append(queue.poll().getKey());
  44.         }
  45.        
  46.         return sb.length() == S.length() ? sb.toString() : "";
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement