原题链接在这里: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. 【实战经验】Xilinx时钟从普通IO输出问题

    Xilinx芯片的时钟信号从普通IO输出时,在map过程中会出错,对此有两种解决方案: 1.在ucf文件中,添加对应的约束文件: 例如[PIN "U0_1/clkout2_buf.O&quo ...

  2. centos7 挂载未分配的硬盘空间

    =============================================== 2019/7/28_第1次修改                       ccb_warlock == ...

  3. sso cas 坑

    一个中文文档地址: http://www.cassso-china.cn/apereo_github_cas_5.2/apereo.github.io/cas/5.2.x/ ============= ...

  4. texlive2019安装

    TeX Live 是 TUG (TeX User Group) 发布并维护的的 TeX 系统,可以称得上是TeX的官方系统,官网为:https://www.tug.org/texlive/ 1.通过最 ...

  5. Java Annontation 注解的学习和理解

    /** * <html> * <body> * <P> Copyright 1994 JsonInternational</p> * <p> ...

  6. 使用 EnumWindows 找到满足你要求的窗口

    原文:使用 EnumWindows 找到满足你要求的窗口 在 Windows 应用开发中,如果需要操作其他的窗口,那么可以使用 EnumWindows 这个 API 来枚举这些窗口. 本文介绍使用 E ...

  7. Tomcat组件梳理—Service组件

    Tomcat组件梳理-Service组件 1.组件定义 Tomcat中只有一个Server,一个Server可以用多个Service,一个Service可以有多个Connector和一个Contain ...

  8. ASP.Net Jquery 随机验证码 文本框判断

    // 登陆验证 $(function () { var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'a', 'B' ...

  9. Tensorflow替换静态图中的OP

    import tensorflow as tf import collections from tensorflow.core.framework import tensor_shape_pb2 # ...

  10. 魅族手机使用应用沙盒一键修改imsi数据

    较早前文章介绍了怎么在安卓手机上安装激活XPosed框架,XPosed框架的牛逼之处功能各位都介绍过,可以不修改apk的前提下,修改系统内核的参数,打比方在某些应用领域,各位需要修改手机的某个系统参数 ...