358 Rearrange String k Distance Apart
1. Question
Given a non-empty stringsand 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:
2. Implementation
(1) Heap
3. Time & Space Complexity
Heap: 时间复杂度O(nlog26) => O(n), 在这题heap存储的元素为26,因为所有字符都是lowercase, 空间复杂度O(n)
Last updated
Was this helpful?