原题链接在这里: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 SchedulerReorganize String.

LeetCode 358. Rearrange String k Distance Apart的更多相关文章

  1. [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 ...

  2. 358. Rearrange String k Distance Apart

    /* * 358. Rearrange String k Distance Apart * 2016-7-14 by Mingyang */ public String rearrangeString ...

  3. 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 ...

  4. 【LeetCode】358. Rearrange String k Distance Apart 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/rearrang ...

  5. [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 ...

  6. 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 ...

  7. [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 ...

  8. [LeetCode] 767. Reorganize String 重构字符串

    Given a string S, check if the letters can be rearranged so that two characters that are adjacent to ...

  9. 【LeetCode】863. All Nodes Distance K in Binary Tree 解题报告(Python)

    [LeetCode]863. All Nodes Distance K in Binary Tree 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http ...

随机推荐

  1. Java开发笔记(一百四十二)JavaFX的对话框

    JavaFX的对话框主要分为提示对话框和文件对话框两类,其中提示对话框又分作消息对话框.警告对话框.错误对话框.确认对话框四种.这四种对话框都使用Alert控件表达,并通过对话框类型加以区分,例如Al ...

  2. Delphi编码与签名【URL编码与解码,Base64编码与解码,MD5加密,HMAC-SHA1、HMAC-SHA224、HMAC-SHA256、HMAC-SHA384和HMAC-SHA512签名】

    作者QQ:(648437169) 点击下载➨delphi编码与签名 [Delphi编码与签名]URL编码与解码,Base64编码与解码,MD5加密,HMAC-SHA1.HMAC-SHA224.HMAC ...

  3. 玩机之HUAWEI_Nova

    Nova是一款挺早的机型了.最开始使用华为就觉得这一款最好挺好用,屏幕小巧功能强大.当然也离不开手机,最早的TWRP就是在此机型上初步尝试成功,也算学习,那时候还没有玩过.这部手机算是改机最完美的一部 ...

  4. Spark之RDD容错原理及四大核心要点

    一.Spark RDD容错原理 RDD不同的依赖关系导致Spark对不同的依赖关系有不同的处理方式. 对于宽依赖而言,由于宽依赖实质是指父RDD的一个分区会对应一个子RDD的多个分区,在此情况下出现部 ...

  5. Selenium+Java(八)Selenium下拉框处理

    Selenium定位下拉框中的元素与普通元素定位有所不同,下面介绍三种定位下拉框元素的方法. 下拉款HTML代码如图所示: 一.通过text定位 //获取下拉框对象 Select city = new ...

  6. 【leetcode-78 dfs+回溯】 子集

    子集 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集). 说明:解集不能包含重复的子集. 示例: 输入: nums = [1,2,3] 输出: [ [3],   [1],   ...

  7. ElasticSearch监控工具 - cerebro

    官方地址:https://github.com/lmenezes/cerebro 需要有java环境 下载地址:https://github.com/lmenezes/cerebro/releases ...

  8. Drools7 Hello Wrold 入门详细步骤--系列01课

    一.什么叫规则引擎?规则--->写在文档上引擎--->在java代码上,引用这个文档上的规则 二.drools规则引擎有什么用?简单来说就是将多变的规则,从业务代码中剥离出来(当规则变了之 ...

  9. java之hibernate之组合主键映射

    1.在应用中经常会有主键是由2个或多个字段组合而成的.比如成绩表: 第一种方式:把主键写为单独的类 2.类的设计:studentId,subjectId ,这两个主键是一个组件.所以可以采用组件映射的 ...

  10. 浅谈分词算法基于字的分词方法(HMM)

    前言 在浅谈分词算法(1)分词中的基本问题我们讨论过基于词典的分词和基于字的分词两大类,在浅谈分词算法(2)基于词典的分词方法文中我们利用n-gram实现了基于词典的分词方法.在(1)中,我们也讨论了 ...