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 ...
随机推荐
- c#学习笔记2-委托
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using S ...
- 修改 Delphi 10.3.3 IDE 字体和字体大小
Delphi 10.2.2 之前,可以通过 IDE视觉设置的系统注册表项 修改字体和字体大小,因为 Delphi 10.2.2 IDE增加了主题,主题包含了字体信息, 此方法失效了.对于高分辨率屏幕, ...
- java知识精要(一)
一.java数组 (疯狂java讲义 第4.5 ~ 4.6章节) 1) 声明形式: type[] arrayName; 推荐方式 type arrayName[]; 2) 初始化: 方式一: type ...
- head first c# -- 第七章 (接口与抽象类)
接口的作用: 例子:有鸡,鸭,牛,羊4个类,还有farmer类: farmer.feed(obj obj) { obj.eat() } // 没有接口: farmer.feedChicken(Chic ...
- Java 的 WebSocket
1. WebSocket 是什么 一言以蔽之,WebSocket允许服务器「主动」给浏览器发消息,如教程演示截图,服务器会主动推送比特币价格给浏览器. 2. 为什么要用 WebSocket 实时获取服 ...
- volatile-最轻量级的并发实现及其内存语义
原文连接:(http://www.studyshare.cn/blog/details/1163/0 ) 一.volatile定义 volatile是java并发编程中修饰类的成员变量.成员属性或者对 ...
- zookerper安装使用教程
转载自 http://blog.java1234.com/blog/articles/379.html 再安装zookeeper之前,我们看下zookeeper简介 https://baike.bai ...
- pandas-07 DataFrame修改index、columns名的方法
pandas-07 DataFrame修改index.columns名的方法 一般常用的有两个方法: 1.使用DataFrame.index = [newName],DataFrame.columns ...
- 【夯实基础】- Java中的fail-fast机制
转载自:Java中的fail-fast机制 遍历删除List中的元素有很多种方法,当运用不当的时候就会产生问题.下面主要看看以下几种遍历删除List中元素的形式: 1.通过普通的for删除删除符合条件 ...
- vue页面跳转拦截器
登录拦截逻辑 第一步:路由拦截 首先在定义路由的时候就需要多添加一个自定义字段requireAuth,用于判断该路由的访问是否需要登录.如果用户已经登录,则顺利进入路由, 否则就进入登录页面.在路由管 ...