标签:
1 public class Solution { 2 public String rearrangeString(String str, int k) { 3 if (k <= 1) { 4 return str; 5 } 6 7 Map<Character, Integer> letters = new HashMap<>(); 8 for (char c : str.toCharArray()) { 9 letters.put(c, letters.getOrDefault(c, 0) + 1); 10 } 11 12 PriorityQueue<Map.Entry<Character, Integer>> startQueue = new PriorityQueue<>(new Comparator<Map.Entry<Character, Integer>>() { 13 @Override 14 public int compare(Map.Entry<Character, Integer> m1, Map.Entry<Character, Integer> m2) { 15 return m2.getValue().compareTo(m1.getValue()); 16 } 17 }); 18 19 for (Map.Entry<Character, Integer> entry: letters.entrySet()) { 20 startQueue.offer(entry); 21 } 22 23 StringBuilder result = new StringBuilder(); 24 LinkedList<Map.Entry<Character, Integer>> backupList = new LinkedList<>(); 25 26 while (!startQueue.isEmpty()) { 27 Map.Entry<Character, Integer> current = startQueue.poll(); 28 result.append(current.getKey()); 29 current.setValue(current.getValue() - 1); 30 backupList.offer(current); 31 32 if (backupList.size() < k) { 33 continue; 34 } 35 36 current = backupList.pollFirst(); 37 if (current.getValue() > 0) { 38 startQueue.offer(current); 39 } 40 } 41 return result.length() == str.length() ? result.toString() : ""; 42 } 43 }
1. do not forget to intialize the data.
Rearrange String k Distance Apart
标签:
原文地址:http://www.cnblogs.com/shuashuashua/p/5620485.html