767. Reorganize String - Medium
Given a string S
, check if the letters can be rearranged so that two characters that are adjacent to each other are not the same.
If possible, output any possible result. If not possible, return the empty string.
Example 1:
Input: S = "aab" Output: "aba"
Example 2:
Input: S = "aaab" Output: ""
Note:
S
will consist of lowercase letters and have length in range[1, 500]
.
扫一遍S统计频率。如果某个字母的个数比S.length()+1的一半还多,无法reorganize,返回空。维护一个max heap,按字母出现的次数排序。
用greedy,每次都用出现次数最多的字母当作下一个字符,并比较是否与sb的最后一个字符相等,若sb为空或者不等,append字符之后,判断一下该字符的次数减一是否大于0,若小于0就不用再offer回max heap了。如果第一次poll出来的字符和sb的最后一个字符相等,再poll一个pair出来,用同样方法处理,记得要把第一次poll出来的pair再offer回去!
时间:O(NlogN),空间:O(N)
class Solution { public String reorganizeString(String S) { HashMap<Character, Integer> map = new HashMap<>(); for(char c : S.toCharArray()) { map.put(c, map.getOrDefault(c, 0) + 1); if(map.get(c) > (S.length() + 1) / 2) return ""; } PriorityQueue<int[]> maxHeap = new PriorityQueue<>((a, b) -> (b[1] - a[1])); for(Map.Entry<Character, Integer> entry : map.entrySet()) { maxHeap.offer(new int[] {entry.getKey(), entry.getValue()}); } StringBuilder sb = new StringBuilder(); while(!maxHeap.isEmpty()) { int[] pair = maxHeap.poll(); if(sb.length() == 0 || sb.charAt(sb.length() - 1) != (char)pair[0]) { sb.append((char)pair[0]); if(--pair[1] > 0) maxHeap.offer(new int[] {pair[0], pair[1]}); } else { int[] pair2 = maxHeap.poll(); sb.append((char)pair2[0]); if(--pair2[1] > 0) maxHeap.offer(new int[] {pair2[0], pair2[1]}); maxHeap.offer(new int[] {pair[0], pair[1]}); } } return sb.toString(); } }