原题链接在这里: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. Word 插入目录详细教程 -- 视频教程(6)

    >> 视频教程链接:B站,速度快,清晰 更多关于插入目录的方法,参看:Word插入目录系列 未完 ...... 点击访问原文(进入后根据右侧标签,快速定位到本文)

  2. 图像变化之Laplacian()函数 and Schaar()滤波及综合例子

    先来  Laplacian()函数 #include<math.h> #include<opencv2/opencv.hpp> #include<string.h> ...

  3. 基于DigitalOcean+LAMP+WordPress搭建个人网站

    1. 注册DigitalOcean并新建主机 为了搭建个人网站首先需要一个可以在公网范围访问的主机,可以选用国内如阿里云.国外如DigitalOcean的各种云主机提供商,这里选用DigitalOce ...

  4. Google Colab——零成本玩转深度学习

    前言 最近在学深度学习HyperLPR项目时,由于一直没有比较合适的设备训练深度学习的模型,所以在网上想找到提供模型训练,经过一段时间的搜索,最终发现了一个谷歌的产品--Google Colabora ...

  5. Linux基础(06)IO复用

    在Windows文件指的就是普通的肉眼可见的文件 , 而Linux一切皆文件 https://blog.csdn.net/nan_nan_nan_nan_nan/article/details/812 ...

  6. FMX 隐藏任务栏 xe10

    找了好多信息,测试好些,xe10  隐藏只要以下命令 隐藏 ShowWindow(ApplicationHWND, SW_HIDE); 显示 ShowWindow(ApplicationHWND, S ...

  7. redis - redis安装与启动

    redis安装 下载redis安装包 wget http://download.redis.io/releases/redis-5.0.7.tar.gz 解压缩 tar -xzf redis-5.0. ...

  8. highcharts离线导出图表

    到了这里,其实还没有结束,导出图片时,仍会发出两个请求 此时找到offline-exporting.js文件修改其中的libURL 修改为请求自己的网站

  9. MVC学习笔记(四)---使用linq多表联查(SQL)

    1.数据库原型(Students表中的ID和Scores表中的StudentID是对应的) 2.实现效果:查询出每个学生各个科目的成绩(用的是MVC学习笔记(三)—用EF向数据库中添加数据的架构) C ...

  10. 微软企业库支持 MySql

    微软企业库支持 MySql   三步让企业库支持 mysql 数据库 1.创建 MySqlDatabaseData 类 using Microsoft.Practices.EnterpriseLibr ...