358. Rearrange String k Distance Apart
package LeetCode_358 import java.util.* import kotlin.collections.ArrayList import kotlin.collections.HashMap /** * 358. Rearrange String k Distance Apart * (Prime) * 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: Input: s = "aabbcc", k = 3 Output: "abcabc" Explanation: The same letters are at least distance 3 from each other. Example 2: Input: s = "aaabc", k = 3 Output: "" Explanation: It is not possible to rearrange the string. Example 3: Input: s = "aaadbbcc", k = 2 Output: "abacabcd" Explanation: The same letters are at least distance 2 from each other. * */ class Solution { /* * solution: HashMap + Priority Queue, Time complexity:O(nlogn), Space complexity:O(n) * 1. calculate frequency of each letter * 2. put all letter into Priority Queue by most freq * 3. take out most freq letter one by one to make tht answer * */ fun rearrrangeString(s: String, k: Int): String { if (k == 0) { return s } val map = HashMap<Char, Int>() for (c in s) { map.put(c, map.getOrDefault(c, 0) + 1) } //set the max heap, store pair, first is frequency, second is char val queue = PriorityQueue<Pair<Int, Char>> { a, b -> if (b.first == a.first) { a.second - b.second } else { b.first - a.first } } map.forEach { char, freq -> queue.add(Pair(freq, char)) } val sb = StringBuilder() while (queue.isNotEmpty()) { //take out first k element val n = Math.min(k, queue.size) val temp = ArrayList<Pair<Int, Char>>() for (i in 0 until n) { val cur = queue.remove() val char = cur.second var freq = cur.first sb.append(char) //check if need put in queue again freq-- if (freq != 0) { temp.add(Pair(freq, char)) } } //check if can same characters at least distance k, if cannot return "" if (n < k && temp.isNotEmpty()) { return "" } //then put some back to queue for (item in temp) { queue.add(item) } } return sb.toString() } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)