Leetcode: Rearrange String k Distance Apart
Given a non-empty string str and an integer k, rearrange the string such that the same characters are at least distance k from each other. All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string "". Example 1:
str = "aabbcc", k = 3 Result: "abcabc" The same letters are at least distance 3 from each other.
Example 2:
str = "aaabc", k = 3 Answer: "" It is not possible to rearrange the string.
Example 3:
str = "aaadbbcc", k = 2 Answer: "abacabcd" Another possible answer is: "abcabcda" The same letters are at least distance 2 from each other.
public class Solution {
public String rearrangeString(String str, int k) {
Map<Character, Integer> map = new HashMap<Character, Integer>();
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
map.put(c, map.getOrDefault(c, 0) + 1);
}
Queue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<>(1, new Comparator<Map.Entry<Character, Integer>>() {
public int compare(Map.Entry<Character, Integer> entry1, Map.Entry<Character, Integer> entry2) {
return entry2.getValue()-entry1.getValue();
} });
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
maxHeap.offer(entry);
}
Queue<Map.Entry<Character, Integer>> waitQueue = new LinkedList<>();
StringBuilder res = new StringBuilder(); while (!maxHeap.isEmpty()) {
Map.Entry<Character, Integer> entry = maxHeap.poll();
res.append(entry.getKey());
entry.setValue(entry.getValue()-1);
waitQueue.offer(entry);
if (waitQueue.size() >= k) {
Map.Entry<Character, Integer> unfreezeEntry = waitQueue.poll();
if (unfreezeEntry.getValue() > 0) maxHeap.offer(unfreezeEntry);
}
}
return res.length()==str.length()? res.toString() : "";
}
}
Solution2: Greedy Using Array, Time Complexity: O(N*26)
public class Solution {
public String rearrangeString(String str, int k) {
int[] count = new int[26];
int[] nextValid = new int[26];
for (int i=0; i<str.length(); i++) {
count[str.charAt(i)-'a']++;
}
StringBuilder res = new StringBuilder();
for (int index=0; index<str.length(); index++) {
int nextCandidate = findNextValid(count, nextValid, index);
if (nextCandidate == -1) return "";
else {
res.append((char)('a' + nextCandidate));
count[nextCandidate]--;
nextValid[nextCandidate] += k;
}
}
return res.toString();
} public int findNextValid(int[] count, int[] nextValid, int index) {
int nextCandidate = -1;
int max = 0;
for (int i=0; i<count.length; i++) {
if (count[i]>max && index>=nextValid[i]) {
max = count[i];
nextCandidate = i;
}
}
return nextCandidate;
}
}
Leetcode: Rearrange String k Distance Apart的更多相关文章
- [LeetCode] Rearrange String k Distance Apart 按距离为k隔离重排字符串
Given a non-empty string str and an integer k, rearrange the string such that the same characters ar ...
- 358. Rearrange String k Distance Apart
/* * 358. Rearrange String k Distance Apart * 2016-7-14 by Mingyang */ public String rearrangeString ...
- LC 358. Rearrange String k Distance Apart
Given a non-empty string s and an integer k, rearrange the string such that the same characters are ...
- LeetCode 358. Rearrange String k Distance Apart
原题链接在这里:https://leetcode.com/problems/rearrange-string-k-distance-apart/description/ 题目: Given a non ...
- [LeetCode] 358. Rearrange String k Distance Apart 按距离k间隔重排字符串
Given a non-empty string str and an integer k, rearrange the string such that the same characters ar ...
- 【LeetCode】358. Rearrange String k Distance Apart 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/rearrang ...
- [Swift]LeetCode358. 按距离为k隔离重排字符串 $ Rearrange String k Distance Apart
Given a non-empty string str and an integer k, rearrange the string such that the same characters ar ...
- [LeetCode] Reorganize String 重构字符串
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to ...
- [leetcode]244. Shortest Word Distance II最短单词距离(允许连环call)
Design a class which receives a list of words in the constructor, and implements a method that takes ...
随机推荐
- JavaScript预解析1
var 不一定是用来定义局部变量的 jscript的全局变量和局部变量的分界是这样的: 过程体(包括方法function,对象Object o ={})外的所有变量不 ...
- linux 查找文件或者内容常用命令
whereis <程序名称> find [路径] <表达式> locate <文件名称> 从文件内容查找匹配指定字符串的行: $ grep "被查找的字符 ...
- hdu4135 容斥定理
Co-prime Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Su ...
- JBD日志的定位、分析和恢复
在上一篇中,我们介绍了Ext3文件系统的日志可以看做一个文件,由JBD进行管理.自然而然引出如下这些问题: 1)如何定位ext3日志文件和查看日志文件的裸数据? 2)ext3日志文件数据在物理上是如何 ...
- 洛谷 P1373 小a和uim之大逃离 Label:dp 不会
题目背景 小a和uim来到雨林中探险.突然一阵北风吹来,一片乌云从北部天边急涌过来,还伴着一道道闪电,一阵阵雷声.刹那间,狂风大作,乌云布满了天空,紧接着豆大的雨点从天空中打落下来,只见前方出现了一个 ...
- POJ 1637 Sightseeing tour(混合图的欧拉回路)
题目链接 建个图,套个模板. #include <cstdio> #include <cstring> #include <iostream> #include & ...
- .net获取DataTable里面的值(asp.net遍历获取datatable的值)
方法一:for (int i =0; i < dtb_xx.Rows.Count; i++ ){response.write dtb_xx.Rows[i]["szxxxx1" ...
- ZeroMQ接口函数之 :zmq_msg_size - 以字节为单位返回消息内容的大小
ZeroMQ 官方地址 :http://api.zeromq.org/4-2:zmq_msg_size zmq_msg_size(3) ØMQ Manual - ØMQ/3.2.5 Name zmq ...
- *cf.4 贪心
D. Kostya the Sculptor time limit per test 3 seconds memory limit per test 256 megabytes input stand ...
- BS中的 data:image/png;base64
举个图片的例子: 网页中一张图片可以这样显示: <img src="http://mail.163.com/images/x.png" /> 也可以这样显示: < ...