LeetCode 358. Rearrange String k Distance Apart
原题链接在这里:https://leetcode.com/problems/rearrange-string-k-distance-apart/description/
题目:
Given a non-empty string s 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:
s = "aabbcc", k = 3 Result: "abcabc" The same letters are at least distance 3 from each other.
Example 2:
s = "aaabc", k = 3 Answer: "" It is not possible to rearrange the string.
Example 3:
s = "aaadbbcc", k = 2 Answer: "abacabcd" Another possible answer is: "abcabcda" The same letters are at least distance 2 from each other.
题解:
Greedy问题. 感觉上是应该先排剩余frequency 最多的Character.
用maxHeap来维护剩余的Character, 根据剩余的count.
那么如何保持断开的距离大于k呢, 用queue来存放已经加过的Character, 只有当queue的size等于k时, 才允许把头上的Character放回到maxHeap中.
Time Complexity: O(nlogn). n = s.length(). 都加入进maxHeap用时O(nlogn).
Space: O(n).
AC Java:
class Solution {
public String rearrangeString(String s, int k) {
if(s == null || s.length() == 0){
return s;
}
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
for(int i = 0; i<s.length(); i++){
hm.put(s.charAt(i), hm.getOrDefault(s.charAt(i), 0)+1);
}
PriorityQueue<Map.Entry<Character, Integer>> maxHeap = new PriorityQueue<Map.Entry<Character, Integer>>(
(a, b) -> b.getValue() - a.getValue()
);
maxHeap.addAll(hm.entrySet());
LinkedList<Map.Entry<Character, Integer>> que = new LinkedList<Map.Entry<Character, Integer>>();
StringBuilder sb = new StringBuilder();
while(!maxHeap.isEmpty()){
Map.Entry<Character, Integer> cur = maxHeap.poll();
sb.append(cur.getKey());
cur.setValue(cur.getValue()-1);
que.add(cur);
if(que.size() < k){
continue;
}
Map.Entry<Character, Integer> head = que.poll();
if(head.getValue() > 0){
maxHeap.add(head);
}
}
return sb.length() == s.length() ? sb.toString() : "";
}
}
时间上可以优化.
利用两个int array, count计数剩余frequency, validPo代表这个字符能出现的最早位置.
找到最大frequency的合法字符, 更新其对应的frequency 和 再次出现的位置.
Time Complexity: O(s.length()). findMaxValidCount走了遍长度为i26的count array.
Space: O(s.length()). StringBuilder size.
AC Java:
class Solution {
public String rearrangeString(String s, int k) {
if(s == null || s.length() == 0){
return s;
}
int [] count = new int[26];
int [] validPo = new int[26];
for(int i = 0; i<s.length(); i++){
count[s.charAt(i)-'a']++;
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i<s.length(); i++){
int po = findMaxValidCount(count, validPo, i);
if(po == -1){
return "";
}
sb.append((char)('a'+po));
count[po]--;
validPo[po] = i+k;
}
return sb.toString();
}
private int findMaxValidCount(int [] count, int [] validPo, int ind){
int po = -1;
int max = Integer.MIN_VALUE;
for(int i = 0; i<count.length; i++){
if(count[i]>0 && count[i]>max && ind>=validPo[i]){
max = count[i];
po = i;
}
}
return po;
}
}
类似Task Scheduler, Reorganize String.
LeetCode 358. Rearrange String k Distance Apart的更多相关文章
- [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 ...
- 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 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/rearrang ...
- [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 ...
- Leetcode: Rearrange String k Distance Apart
Given a non-empty string str and an integer k, rearrange the string such that the same characters ar ...
- [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] 767. Reorganize String 重构字符串
Given a string S, check if the letters can be rearranged so that two characters that are adjacent to ...
- 【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)
[LeetCode]863. All Nodes Distance K in Binary Tree 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http ...
随机推荐
- Go语言(环境的搭建)
一步一步,从零搭建Go语言开发环境. 安装Go语言及搭建Go语言开发环境 下载 下载地址 Go官网下载地址:https://golang.org/dl/ Go官方镜像站(推荐):https://gol ...
- PB 选择继承父类的注意事项
1.父类的datewindow 的祖先类最好不是n_dw_single ,最好是n_dw_grid,n_dw_single 的标题行没有阴影.排序,没有行聚焦等功能(非常初始的).n_dw_grid ...
- Java 阿拉伯数字转换为中文大写数字
Java 阿拉伯数字转换为中文大写数字 /** * <html> * <body> * <P> Copyright 1994 JsonInternational&l ...
- NMS(non maximum suppression,非极大值抑制)
"""nms输入的数据为box的左上角x1,y1与右下角x2,y2+confidence,rows=batch_size,line=[x1,y1,x2,y2,confid ...
- 关于AWK的10个经典案例
awk是Linux系统下一个处理文本的编程语言工具,能用简短的程序处理标准输入或文件.数据排序.计算以及生成报表等等,应用非常广泛.基本的命令语法:awk option 'pattern {actio ...
- js模块基础练习题
题目描述 完成函数 createModule,调用之后满足如下要求: 1.返回一个对象 2.对象的 greeting 属性值等于 str1, name 属性值等于 str2 3.对象存在一个 sayI ...
- 深入理解es6(上)
一.let和const 1.let与var的区别 不存在变量提升 块级作用域 不允许重复声明 2.const常量 const与let一样,唯一区别在于声明的常量不能被修改 二.解构赋值 es6按照一定 ...
- thrift java first demo
参考文档:http://thrift.apache.org/ 1.下载需要的文件 地址:http://thrift.apache.org/download 需要下载 thrift-0.12.0.ta ...
- Oracle 数据块
以emp表为例 SYS@ prod>select * from scott.emp; EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO --------- ...
- 多线程之美6一CAS与自旋锁
1.什么是CAS CAS 即 compare and swap 比较并交换, 涉及到三个参数,内存值V, 预期值A, 要更新为的值B, 拿着预期值A与内存值V比较,相等则符合预期,将内存值V更新为B, ...