@@ -29,15 +29,15 @@ tags:
2929
3030<pre >
3131<strong >输入: </strong >s = "aabbcc", k = 3
32- <strong >输出: </strong >"abcabc"
32+ <strong >输出: </strong >"abcabc"
3333<strong >解释: </strong >相同的字母在新的字符串中间隔至少 3 个单位距离。
3434</pre >
3535
3636<p ><strong >示例 2:</strong ></p >
3737
3838<pre >
3939<strong >输入: </strong >s = "aaabc", k = 3
40- <strong >输出: </strong >""
40+ <strong >输出: </strong >""
4141<strong >解释:</strong > 没有办法找到可能的重排结果。
4242</pre >
4343
@@ -67,13 +67,13 @@ tags:
6767
6868### 方法一:贪心 + 哈希表 + 优先队列(大根堆)
6969
70- 先用哈希表 ` cnt ` 统计每个字母出现的次数,然后构建一个大根堆 ` pq ` ,其中每个元素是一个 ` (v, c) ` 的元组 ,其中 ` c ` 是字母, ` v ` 是字母出现的次数 。
70+ 我们用一个哈希表或数组 $\textit{ cnt}$ 来统计字符串中每个字母出现的次数,然后用一个大根堆 $\textit{pq}$ 来存储每个字母及其出现次数。堆中的每个元素是一个二元组 $ (v, c)$ ,其中 $v$ 和 $c$ 分别表示字母出现的次数和字母本身 。
7171
72- 重排字符串时 ,我们每次从堆顶弹出一个元素 ` (v, c) ` ,将 ` c ` 添加到结果字符串中,并将 ` (v-1, c) ` 放入队列 ` q ` 中。当队列 ` q ` 的长度达到 $k$ 及以上时,弹出队首元素,若此时 ` v ` 大于 0,则将队首元素放入堆中。循环,直至堆为空 。
72+ 在重排字符串时 ,我们每次从堆顶弹出一个元素 $ (v, c)$,将字母 $c$ 添加到结果字符串中,并将 $ (v-1, c)$ 放入一个队列 $\textit{q}$ 中。当队列 $\textit{q}$ 的长度达到 $k$ 及以上时,弹出队首元素,若此时 $v$ 大于 $0$,则将队首元素重新放入堆中。重复该过程,直到堆为空 。
7373
74- 最后判断结果字符串的长度,若与 ` s ` 长度相等,则返回结果字符串 ,否则返回空串。
74+ 最后,我们判断结果字符串的长度是否与原字符串相等,若相等则返回结果字符串 ,否则返回空串。
7575
76- 时间复杂度 $O(n\log n)$,其中 $n$ 是字符串 ` s ` 的长度 。
76+ 时间复杂度为 $O(n \log n)$,其中 $n$ 是字符串的长度。空间复杂度 $O(|\Sigma|)$,其中 $|\Sigma|$ 是字符集的大小,本题中 $|\Sigma| = 26$ 。
7777
7878相似题目:
7979
@@ -86,34 +86,33 @@ tags:
8686``` python
8787class Solution :
8888 def rearrangeString (self , s : str , k : int ) -> str :
89- h = [(- v, c) for c, v in Counter(s).items()]
90- heapify(h)
89+ cnt = Counter(s)
90+ pq = [(- v, c) for c, v in cnt.items()]
91+ heapify(pq)
9192 q = deque()
9293 ans = []
93- while h:
94- v, c = heappop(h)
95- v *= - 1
94+ while pq:
95+ v, c = heappop(pq)
9696 ans.append(c)
97- q.append((v - 1 , c))
97+ q.append((v + 1 , c))
9898 if len (q) >= k:
99- w, c = q.popleft()
100- if w :
101- heappush(h, ( - w, c) )
102- return " " if len (ans) != len (s) else " " .join(ans)
99+ e = q.popleft()
100+ if e[ 0 ] :
101+ heappush(pq, e )
102+ return " " if len (ans) < len (s) else " " .join(ans)
103103```
104104
105105#### Java
106106
107107``` java
108108class Solution {
109109 public String rearrangeString (String s , int k ) {
110- int n = s. length();
111110 int [] cnt = new int [26 ];
112111 for (char c : s. toCharArray()) {
113112 ++ cnt[c - ' a' ];
114113 }
115114 PriorityQueue<int[]> pq = new PriorityQueue<> ((a, b) - > b[0 ] - a[0 ]);
116- for (int i = 0 ; i < 26 ; ++ i) {
115+ for (int i = 0 ; i < cnt . length ; ++ i) {
117116 if (cnt[i] > 0 ) {
118117 pq. offer(new int [] {cnt[i], i});
119118 }
@@ -122,17 +121,17 @@ class Solution {
122121 StringBuilder ans = new StringBuilder ();
123122 while (! pq. isEmpty()) {
124123 var p = pq. poll();
125- int v = p[0 ], c = p[ 1 ] ;
126- ans. append((char ) (' a' + c ));
127- q. offer( new int [] {v - 1 , c} );
124+ p[0 ] -= 1 ;
125+ ans. append((char ) (' a' + p[ 1 ] ));
126+ q. offerLast(p );
128127 if (q. size() >= k) {
129128 p = q. pollFirst();
130129 if (p[0 ] > 0 ) {
131130 pq. offer(p);
132131 }
133132 }
134133 }
135- return ans. length() == n ? ans. toString() : " " ;
134+ return ans. length() < s . length() ? " " : ans. toString();
136135 }
137136}
138137```
@@ -143,26 +142,36 @@ class Solution {
143142class Solution {
144143public:
145144 string rearrangeString(string s, int k) {
146- unordered_map<char, int> cnt;
147- for (char c : s) ++cnt[ c] ;
148- priority_queue<pair<int, char>> pq;
149- for (auto& [ c, v] : cnt) pq.push({v, c});
150- queue<pair<int, char>> q;
145+ vector<int > cnt(26, 0);
146+ for (char c : s) {
147+ ++cnt[ c - 'a'] ;
148+ }
149+
150+ priority_queue<pair<int, int>> pq;
151+ for (int i = 0; i < 26; ++i) {
152+ if (cnt[i] > 0) {
153+ pq.emplace(cnt[i], i);
154+ }
155+ }
156+
157+ queue<pair<int , int >> q;
151158 string ans;
152159 while (!pq.empty()) {
153- auto [ v, c ] = pq.top();
160+ auto p = pq.top();
154161 pq.pop();
155- ans += c;
156- q.push({v - 1, c});
162+ p.first -= 1;
163+ ans.push_back('a' + p.second);
164+ q.push(p);
157165 if (q.size() >= k) {
158- auto p = q.front();
166+ p = q.front();
159167 q.pop();
160- if (p.first) {
168+ if (p.first > 0 ) {
161169 pq.push(p);
162170 }
163171 }
164172 }
165- return ans.size() == s.size() ? ans : "";
173+
174+ return ans.size() < s.size() ? "" : ans;
166175 }
167176};
168177```
@@ -171,50 +180,80 @@ public:
171180
172181``` go
173182func rearrangeString (s string , k int ) string {
174- cnt := map[byte ]int{}
175- for i := range s {
176- cnt[s[i] ]++
183+ cnt := [ 26 ]int {}
184+ for _ , c := range s {
185+ cnt[c- ' a ' ]++
177186 }
178- pq := hp{}
179- for c, v := range cnt {
180- heap.Push(&pq, pair{v, c})
187+ pq := priorityqueue.NewWith (func (a, b any) int {
188+ x := a.([2 ]int )
189+ y := b.([2 ]int )
190+ return y[0 ] - x[0 ]
191+ })
192+
193+ for i := 0 ; i < 26 ; i++ {
194+ if cnt[i] > 0 {
195+ pq.Enqueue ([2 ]int {cnt[i], i})
196+ }
181197 }
182- ans := []byte{}
183- q := []pair{}
184- for len(pq) > 0 {
185- p := heap.Pop(&pq).(pair)
186- v, c := p.v, p.c
187- ans = append(ans, c)
188- q = append(q, pair{v - 1, c})
198+
199+ var q [][2 ]int
200+ var ans strings.Builder
201+
202+ for pq.Size () > 0 {
203+ p , _ := pq.Dequeue ()
204+ pair := p.([2 ]int )
205+ pair[0 ]--
206+ ans.WriteByte (byte (' a' + pair[1 ]))
207+ q = append (q, pair)
208+
189209 if len (q) >= k {
190- p = q[0]
210+ front : = q[0 ]
191211 q = q[1 :]
192- if p.v > 0 {
193- heap.Push(&pq, p )
212+ if front[ 0 ] > 0 {
213+ pq. Enqueue (front )
194214 }
195215 }
196216 }
197- if len(ans) == len(s) {
198- return string(ans)
217+
218+ if ans.Len () < len (s) {
219+ return " "
199220 }
200- return ""
221+ return ans. String ()
201222}
223+ ```
202224
203- type pair struct {
204- v int
205- c byte
206- }
225+ #### TypeScript
226+
227+ ``` ts
228+ export function rearrangeString(s : string , k : number ): string {
229+ const cnt: number [] = Array (26 ).fill (0 );
230+ for (const c of s ) {
231+ cnt [c .charCodeAt (0 ) - ' a' .charCodeAt (0 )]++ ;
232+ }
207233
208- type hp []pair
234+ const pq = new PriorityQueue <[number , number ]>((a , b ) => b [0 ] - a [0 ]);
235+ for (let i = 0 ; i < 26 ; i ++ ) {
236+ if (cnt [i ] > 0 ) {
237+ pq .enqueue ([cnt [i ], i ]);
238+ }
239+ }
209240
210- func (h hp) Len() int { return len(h) }
211- func (h hp) Less(i, j int) bool {
212- a, b := h[i], h[j]
213- return a.v > b.v
241+ const q: [number , number ][] = [];
242+ const ans: string [] = [];
243+ while (! pq .isEmpty ()) {
244+ const [count, idx] = pq .dequeue ()! ;
245+ const newCount = count - 1 ;
246+ ans .push (String .fromCharCode (' a' .charCodeAt (0 ) + idx ));
247+ q .push ([newCount , idx ]);
248+ if (q .length >= k ) {
249+ const [frontCount, frontIdx] = q .shift ()! ;
250+ if (frontCount > 0 ) {
251+ pq .enqueue ([frontCount , frontIdx ]);
252+ }
253+ }
254+ }
255+ return ans .length < s .length ? ' ' : ans .join (' ' );
214256}
215- func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
216- func (h *hp) Push(v any) { *h = append(*h, v.(pair)) }
217- func (h *hp) Pop() any { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
218257```
219258
220259<!-- tabs:end -->
0 commit comments