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 ...
随机推荐
- Latex中如何设置字体颜色(三种方式)
1.直接使用定义好的颜色 \usepackage{color} \textcolor{red/blue/green/black/white/cyan/magenta/yellow}{text} 其中t ...
- 安装macOS时遇到Unable to unmount volume for repair异常导致无法完成安装的解决办法
方法一: 使用终端命令行制作完macos安装U盘后,务必将.IAProductInfo文件放到U盘的根目录(非EFI分区的) sudo /Applications/Install\ macOS\ Si ...
- 论文笔记: Matrix Factorization Techniques For Recommender Systems
Recommender system strategies 通过例子简单介绍了一下 collaborative filtering 以及latent model,这两个方法在之前的博客里面介绍过,不累 ...
- Python 将中文、字母转成数字
Outline 把中文汉字或者英文字母或者特殊字符转换成数字. (实质是字符转成对应ASCII码) 转换 将中文汉字转成数字: ord('单个中文汉字') 反转: chr(21704) 将英文字母转成 ...
- CentOS -- 新建用户并使能密钥登录
目录 1. 新建用户 2. 为新用户授权 2.1. 方法一:把新用户添加到wheel用户组中 2.2. 方法二:把新用户添加到sudoers列表中 3. 新用户使能 SSH 密钥登录 4. 其它 4. ...
- Java 之 Maven 基础
一.Maven 介绍 1.什么是 Maven Maven 是一个项目管理工具,它包含了一个项目对象模型(POM:Project Object Model),一组标准集合,一个项目生命周期(Projec ...
- Joomla漏洞复现
漏洞环境及利用 Joomla 3.4.6 : https://downloads.joomla.org/it/cms/joomla3/3-4-6 PHP 版本: 5.5.38 Joomla 3.4 之 ...
- HttpClient实战三:Spring整合HttpClient连接池
简介 在微服务架构或者REST API项目中,使用Spring管理Bean是很常见的,在项目中HttpClient使用的一种最常见方式就是:使用Spring容器XML配置方式代替Java编码方式进行H ...
- union的使用
将多条select语句的结果,合并到一起,称为联合查询 使用union关键字 场景: 获取数据的条件,出现逻辑冲突,或者很难在一个逻辑内表示,就可以拆成多个逻辑,分别实现,最后将结果合并到一起 sel ...
- eclipse svn 提交、更新报错
问题描述: svn: Unable to connect to a repository at URL 'https://test.com/svn/clouds/trunk/fire_Alarm'sv ...