ID | Title | Difficulty | |
---|---|---|---|
Loading... |
767. Reorganize String
Medium
LeetCode
Hash Table, String, Greedy, Sorting, Heap (Priority Queue), Counting
Problem
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: ""
Constraints:
- 1 <= s.length <= 500
- s consists of lowercase English letters.
Code
class Solution {
public String reorganizeString(String S) {
Map<Character, Integer> map = new HashMap<>();
for (char c : S.toCharArray()) {
int count = map.getOrDefault(c, 0) + 1;
if (count > (S.length() + 1) / 2) return "";
map.put(c, count);
}
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[1] - a[1]);
for (char c : map.keySet()) {
pq.add(new int[]{c, map.get(c)});
}
StringBuilder sb = new StringBuilder();
while (!pq.isEmpty()) {
int[] first = pq.poll();
if (sb.length() == 0 || first[0] != sb.charAt(sb.length() - 1)) {
sb.append((char) first[0]);
if (--first[1] > 0) {
pq.add(first);
}
} else {
int[] second = pq.poll();
sb.append((char) second[0]);
if (--second[1] > 0) {
pq.add(second);
}
pq.add(first);
}
}
return sb.toString();
}
}
按 <- 键看上一题!
766. Toeplitz Matrix
按 -> 键看下一题!
769. Max Chunks To Make Sorted