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 ...
随机推荐
- Elasticsearch进阶篇(一)~head插件的安装与配置
1.安装node.js 1.1.通过官网下载二进制安装包 https://nodejs.org/en/download/ 选择对应的版本,右键复制下载链接,进入linux目录,切换到要安装目录的磁盘. ...
- Go语言【开发】加载JSON配置文件
JSON配置加载 辅助网址,JSON转结构体对应 http://json2struct.mervine.net/ 从JSON文件中加载配置到全局变量中 配置文件 config.json { &quo ...
- js 数组传统方法
js 数组传统方法 push() 功能:向数组的末尾添加一个或多个元素 var arr = [4]; arr.push(1,2,3); // [4,1,2,3] 返回: 会返回新数组的长度length ...
- Rust 智能指针(二)
1. Rc<T> 引用计数指针 Rc<T> 是引用计数指针,可以使用clone使得指针所指向的数据具有多个所有者. enum List { Cons(i32, Rc<Li ...
- python代码执行SQL文件(逐句执行)
一.简介 关于Python如何连接数据库并执行SQL语句,几乎所有的Python教程都会讲,教程里基本只介绍了执行单条SQL语句的方法,但是实际生产过程中可不只是执行一两条语句,动辄几十条甚至上百条的 ...
- swift版 二分查找 (折半查找)
二分查找作为一种常见的查找方法,将原本是线性时间提升到了对数时间范围之内,大大缩短了搜索时间,但它有一个前提,就是必须在有序数据中进行查找.废话少说,直接上代码,可复制粘贴直接出结果! import ...
- 魔法 [线段树优化DP]
也许更好的阅读体验 \(\mathcal{Description}\) 小 \(D\) 正在研究魔法. 小 \(D\) 得到了远古时期的魔法咒语 \(S\),这个咒语共有 \(n\) 个音节,每个音节 ...
- JavaScript 的 深拷贝和浅拷贝
深拷贝和浅拷贝都是针对的引用类型, JS中的变量类型分为值类型(基本类型)和引用类型: 对值类型进行复制操作会对值进行一份拷贝,而对引用类型赋值,则会对地址进行拷贝,最终两个变量指向同一份数据 一.先 ...
- PropTypes.element和PropTypes.node的区别
PropTypes.element:指React Element,即React.CreateElement生成的元素,React.CreateElement可以用jsx语法糖表示: <MyBut ...
- Linq Left Join;linq左连接 (转载)
来源 https://www.cnblogs.com/xinjian/archive/2010/11/17/1879959.html 准备一些测试数据,如下: use Test Create tabl ...