原题链接在这里: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. Python学习之路:函数传递可变参数与不可变参数

    函数传参的方法: 太基础了,8说了 直接上重点 一.可变参数的传递 可变参数有:列表.集合.字典 直接上代码: a = [1, 2] def fun(a): print('传入函数时a的值为:', a ...

  2. RWMutex:共享/专有的递归互斥锁

    具有共享/独占访问权限,且具有升级/降级功能的互斥锁 介绍 我的目标是创建可以充当读/写锁定机制的对象.任何线程都可以锁定它以进行读取,但是只有一个线程可以锁定它以进行写入.在写入线程释放它之前,所有 ...

  3. SonarQube安装教程与简单使用(基于Centos7,JDK1.8)

    SonarQube 若要转载本文,请务必声明出处:https://www.cnblogs.com/zhongyuanzhao000/p/11686522.html 概念: SonarQube是一种自动 ...

  4. 前台调用微信接口成功还报Network Error

    前台   vue+springboot项目 this.api({ url:"https://.....",//微信路径 method:"post", param ...

  5. 查看Linux服务器配置

    1.查看CPU lscpu 2.查看内存 free -g 或 free -m 3.查看硬盘 df -h

  6. WPF 程序鼠标在窗口之外的时候,控件拿到的鼠标位置在哪里?

    原文:WPF 程序鼠标在窗口之外的时候,控件拿到的鼠标位置在哪里? 在 WPF 程序中,我们有 Mouse.GetPosition(IInputElement relativeTo) 方法可以拿到鼠标 ...

  7. windows 系统防火墙 添加端口号方法

    目前在大部分公司内使用的台式机和部分服务器都采用了Windows操作系统,而我么都知道相当一部分病毒.恶意程序.黑客都是利用扫描端口号,利用开放的端口进行入侵,此时大型企业都会将服务器的系统防火墙打开 ...

  8. .net Dapper 学习系列(2) ---Dapper进阶

    目录 写在前面 前期准备 Dapper 单表批量添加 在Dapper 多表查询 在Dapper 调用存储过程 在Dapper 使用QueryMultiple进行多表查询 在Dapper 使用事务进行多 ...

  9. 【转载】C#中使用float.TryParse方法将字符串转换为Float类型

    在C#编程过程中,将字符串string转换为单精度float类型过程中,时常使用float.Parse方法,但float.Parse在无法转换的时候,会抛出程序异常,其实还有个float.TryPar ...

  10. Guava Cache用法介绍

    背景 缓存的主要作用是暂时在内存中保存业务系统的数据处理结果,并且等待下次访问使用.在日长开发有很多场合,有一些数据量不是很大,不会经常改动,并且访问非常频繁.但是由于受限于硬盘IO的性能或者远程网络 ...