767. 重构字符串
给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。
若可行,输出任意可行的结果。若不可行,返回空字符串。
示例 1:
输入: S = "aab"
输出: "aba"
示例 2:
输入: S = "aaab"
输出: ""
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorganize-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;
class Solution {
private int[] findTop2(int[] cnt) {
PriorityQueue queue = new PriorityQueue<>(new Comparator() {
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(cnt[o1], cnt[o2]);
}
});
for (int i = 0; i < cnt.length; ++i) {
if (cnt[i] != 0) {
if (queue.size() != 2) {
queue.offer(i);
} else {
if (cnt[queue.peek()] < cnt[i]) {
queue.poll();
queue.offer(i);
}
}
}
}
if (queue.size() == 2) {
int left = queue.poll(), right = queue.poll();
if (cnt[left] == cnt[right]) {
return new int[]{Math.min(left, right), Math.max(left, right)};
}
return new int[]{right, left};
} else {
return new int[]{queue.poll(), -1};
}
}
public String reorganizeString(String s) {
int limit = s.length() / 2 + (s.length() & 1);
int[] cnt = new int[26];
for (int i = 0; i < s.length(); ++i) {
cnt[s.charAt(i) - 'a']++;
if (cnt[s.charAt(i) - 'a'] > limit) {
return "";
}
}
char[] ans = new char[s.length()];
int index = 0;
while (index < s.length()) {
int[] top2 = findTop2(cnt);
ans[index] = (char) (top2[0] + 'a');
cnt[top2[0]]--;
if (top2[1] != -1) {
ans[index + 1] = (char) (top2[1] + 'a');
cnt[top2[1]]--;
}
index += 2;
}
return new String(ans);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
System.out.println(new Solution().reorganizeString(in.next()));
}
}
}