@@ -67,13 +67,13 @@ tags:
67
67
68
68
### 方法一:贪心 + 哈希表 + 优先队列(大根堆)
69
69
70
- 先用哈希表 ` cnt ` 统计每个字母出现的次数,然后构建一个大根堆 ` pq ` ,其中每个元素是一个 ` (v, c) ` 的元组 ,其中 ` c ` 是字母, ` v ` 是字母出现的次数 。
70
+ 我们用一个哈希表或数组 $\textit{ cnt}$ 来统计字符串中每个字母出现的次数,然后用一个大根堆 $\textit{pq}$ 来存储每个字母及其出现次数。堆中的每个元素是一个二元组 $ (v, c)$ ,其中 $v$ 和 $c$ 分别表示字母出现的次数和字母本身 。
71
71
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$,则将队首元素重新放入堆中。重复该过程,直到堆为空 。
73
73
74
- 最后判断结果字符串的长度,若与 ` s ` 长度相等,则返回结果字符串 ,否则返回空串。
74
+ 最后,我们判断结果字符串的长度是否与原字符串相等,若相等则返回结果字符串 ,否则返回空串。
75
75
76
- 时间复杂度 $O(n\log n)$,其中 $n$ 是字符串 ` s ` 的长度 。
76
+ 时间复杂度为 $O(n \log n)$,其中 $n$ 是字符串的长度。空间复杂度 $O(|\Sigma|)$,其中 $|\Sigma|$ 是字符集的大小,本题中 $|\Sigma| = 26$ 。
77
77
78
78
相似题目:
79
79
@@ -86,34 +86,33 @@ tags:
86
86
``` python
87
87
class Solution :
88
88
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)
91
92
q = deque()
92
93
ans = []
93
- while h:
94
- v, c = heappop(h)
95
- v *= - 1
94
+ while pq:
95
+ v, c = heappop(pq)
96
96
ans.append(c)
97
- q.append((v - 1 , c))
97
+ q.append((v + 1 , c))
98
98
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)
103
103
```
104
104
105
105
#### Java
106
106
107
107
``` java
108
108
class Solution {
109
109
public String rearrangeString (String s , int k ) {
110
- int n = s. length();
111
110
int [] cnt = new int [26 ];
112
111
for (char c : s. toCharArray()) {
113
112
++ cnt[c - ' a' ];
114
113
}
115
114
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) {
117
116
if (cnt[i] > 0 ) {
118
117
pq. offer(new int [] {cnt[i], i});
119
118
}
@@ -122,17 +121,17 @@ class Solution {
122
121
StringBuilder ans = new StringBuilder ();
123
122
while (! pq. isEmpty()) {
124
123
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 );
128
127
if (q. size() >= k) {
129
128
p = q. pollFirst();
130
129
if (p[0 ] > 0 ) {
131
130
pq. offer(p);
132
131
}
133
132
}
134
133
}
135
- return ans. length() == n ? ans. toString() : " " ;
134
+ return ans. length() < s . length() ? " " : ans. toString();
136
135
}
137
136
}
138
137
```
@@ -143,26 +142,36 @@ class Solution {
143
142
class Solution {
144
143
public:
145
144
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;
151
158
string ans;
152
159
while (!pq.empty()) {
153
- auto [ v, c ] = pq.top();
160
+ auto p = pq.top();
154
161
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);
157
165
if (q.size() >= k) {
158
- auto p = q.front();
166
+ p = q.front();
159
167
q.pop();
160
- if (p.first) {
168
+ if (p.first > 0 ) {
161
169
pq.push(p);
162
170
}
163
171
}
164
172
}
165
- return ans.size() == s.size() ? ans : "";
173
+
174
+ return ans.size() < s.size() ? "" : ans;
166
175
}
167
176
};
168
177
```
@@ -171,50 +180,80 @@ public:
171
180
172
181
``` go
173
182
func 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 ' ]++
177
186
}
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
+ }
181
197
}
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
+
189
209
if len (q) >= k {
190
- p = q[0]
210
+ front : = q[0 ]
191
211
q = q[1 :]
192
- if p.v > 0 {
193
- heap.Push(&pq, p )
212
+ if front[ 0 ] > 0 {
213
+ pq. Enqueue (front )
194
214
}
195
215
}
196
216
}
197
- if len(ans) == len(s) {
198
- return string(ans)
217
+
218
+ if ans.Len () < len (s) {
219
+ return " "
199
220
}
200
- return ""
221
+ return ans. String ()
201
222
}
223
+ ```
202
224
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
+ }
207
233
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
+ }
209
240
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 (' ' );
214
256
}
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 }
218
257
```
219
258
220
259
<!-- tabs:end -->
0 commit comments