Skip to content

Commit 26c5566

Browse files
committed
feat: add solutions to lc problems: No.0358,0767
* No.0358.Rearrange String k Distance Apart * No.0767.Reorganize String
1 parent 813b3ef commit 26c5566

File tree

8 files changed

+676
-2
lines changed

8 files changed

+676
-2
lines changed

solution/0300-0399/0358.Rearrange String k Distance Apart/README.md

Lines changed: 137 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,22 +48,158 @@
4848

4949
<!-- 这里可写通用的实现逻辑 -->
5050

51+
**方法一:贪心 + 哈希表 + 优先队列(大根堆)**
52+
53+
先用哈希表 `cnt` 统计每个字母出现的次数,然后构建一个大根堆 `pq`,其中每个元素是一个 `(v, c)` 的元组,其中 `c` 是字母,`v` 是字母出现的次数。
54+
55+
重排字符串时,我们每次从堆顶弹出一个元素 `(v, c)`,将 `c` 添加到结果字符串中,并将 `(v-1, c)` 放入队列 `q` 中。当队列 `q` 的长度达到 $k$ 及以上时,弹出队首元素,若此时 `v` 大于 0,则将队首元素放入堆中。循环,直至堆为空。
56+
57+
最后判断结果字符串的长度,若与 `s` 长度相等,则返回结果字符串,否则返回空串。
58+
59+
时间复杂度 $O(n\log n)$,其中 $n$ 是字符串 `s` 的长度。
60+
61+
相似题目:[767. 重构字符串](/solution/0700-0799/0767.Reorganize%20String/README.md)
62+
5163
<!-- tabs:start -->
5264

5365
### **Python3**
5466

5567
<!-- 这里可写当前语言的特殊实现逻辑 -->
5668

5769
```python
58-
70+
class Solution:
71+
def rearrangeString(self, s: str, k: int) -> str:
72+
h = [(-v, c) for c, v in Counter(s).items()]
73+
heapify(h)
74+
q = deque()
75+
ans = []
76+
while h:
77+
v, c = heappop(h)
78+
v *= -1
79+
ans.append(c)
80+
q.append((v - 1, c))
81+
if len(q) >= k:
82+
w, c = q.popleft()
83+
if w:
84+
heappush(h, (-w, c))
85+
return "" if len(ans) != len(s) else "".join(ans)
5986
```
6087

6188
### **Java**
6289

6390
<!-- 这里可写当前语言的特殊实现逻辑 -->
6491

6592
```java
93+
class Solution {
94+
public String rearrangeString(String s, int k) {
95+
int n = s.length();
96+
int[] cnt = new int[26];
97+
for (char c : s.toCharArray()) {
98+
++cnt[c - 'a'];
99+
}
100+
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]);
101+
for (int i = 0; i < 26; ++i) {
102+
if (cnt[i] > 0) {
103+
pq.offer(new int[] {cnt[i], i});
104+
}
105+
}
106+
Deque<int[]> q = new ArrayDeque<>();
107+
StringBuilder ans = new StringBuilder();
108+
while (!pq.isEmpty()) {
109+
var p = pq.poll();
110+
int v = p[0], c = p[1];
111+
ans.append((char) ('a' + c));
112+
q.offer(new int[] {v - 1, c});
113+
if (q.size() >= k) {
114+
p = q.pollFirst();
115+
if (p[0] > 0) {
116+
pq.offer(p);
117+
}
118+
}
119+
}
120+
return ans.length() == n ? ans.toString() : "";
121+
}
122+
}
123+
```
124+
125+
### **C++**
126+
127+
```cpp
128+
class Solution {
129+
public:
130+
string rearrangeString(string s, int k) {
131+
unordered_map<char, int> cnt;
132+
for (char c : s) ++cnt[c];
133+
priority_queue<pair<int, char>> pq;
134+
for (auto& [c, v] : cnt) pq.push({v, c});
135+
queue<pair<int, char>> q;
136+
string ans;
137+
while (!pq.empty()) {
138+
auto [v, c] = pq.top();
139+
pq.pop();
140+
ans += c;
141+
q.push({v - 1, c});
142+
if (q.size() >= k) {
143+
auto p = q.front();
144+
q.pop();
145+
if (p.first) {
146+
pq.push(p);
147+
}
148+
}
149+
}
150+
return ans.size() == s.size() ? ans : "";
151+
}
152+
};
153+
```
66154
155+
### **Go**
156+
157+
```go
158+
func rearrangeString(s string, k int) string {
159+
cnt := map[byte]int{}
160+
for i := range s {
161+
cnt[s[i]]++
162+
}
163+
pq := hp{}
164+
for c, v := range cnt {
165+
heap.Push(&pq, pair{v, c})
166+
}
167+
ans := []byte{}
168+
q := []pair{}
169+
for len(pq) > 0 {
170+
p := heap.Pop(&pq).(pair)
171+
v, c := p.v, p.c
172+
ans = append(ans, c)
173+
q = append(q, pair{v - 1, c})
174+
if len(q) >= k {
175+
p = q[0]
176+
q = q[1:]
177+
if p.v > 0 {
178+
heap.Push(&pq, p)
179+
}
180+
}
181+
}
182+
if len(ans) == len(s) {
183+
return string(ans)
184+
}
185+
return ""
186+
}
187+
188+
type pair struct {
189+
v int
190+
c byte
191+
}
192+
193+
type hp []pair
194+
195+
func (h hp) Len() int { return len(h) }
196+
func (h hp) Less(i, j int) bool {
197+
a, b := h[i], h[j]
198+
return a.v > b.v
199+
}
200+
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
201+
func (h *hp) Push(v interface{}) { *h = append(*h, v.(pair)) }
202+
func (h *hp) Pop() interface{} { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
67203
```
68204

69205
### **...**

solution/0300-0399/0358.Rearrange String k Distance Apart/README_EN.md

Lines changed: 125 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,137 @@
4747
### **Python3**
4848

4949
```python
50-
50+
class Solution:
51+
def rearrangeString(self, s: str, k: int) -> str:
52+
h = [(-v, c) for c, v in Counter(s).items()]
53+
heapify(h)
54+
q = deque()
55+
ans = []
56+
while h:
57+
v, c = heappop(h)
58+
v *= -1
59+
ans.append(c)
60+
q.append((v - 1, c))
61+
if len(q) >= k:
62+
w, c = q.popleft()
63+
if w:
64+
heappush(h, (-w, c))
65+
return "" if len(ans) != len(s) else "".join(ans)
5166
```
5267

5368
### **Java**
5469

5570
```java
71+
class Solution {
72+
public String rearrangeString(String s, int k) {
73+
int n = s.length();
74+
int[] cnt = new int[26];
75+
for (char c : s.toCharArray()) {
76+
++cnt[c - 'a'];
77+
}
78+
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> b[0] - a[0]);
79+
for (int i = 0; i < 26; ++i) {
80+
if (cnt[i] > 0) {
81+
pq.offer(new int[] {cnt[i], i});
82+
}
83+
}
84+
Deque<int[]> q = new ArrayDeque<>();
85+
StringBuilder ans = new StringBuilder();
86+
while (!pq.isEmpty()) {
87+
var p = pq.poll();
88+
int v = p[0], c = p[1];
89+
ans.append((char) ('a' + c));
90+
q.offer(new int[] {v - 1, c});
91+
if (q.size() >= k) {
92+
p = q.pollFirst();
93+
if (p[0] > 0) {
94+
pq.offer(p);
95+
}
96+
}
97+
}
98+
return ans.length() == n ? ans.toString() : "";
99+
}
100+
}
101+
```
102+
103+
### **C++**
104+
105+
```cpp
106+
class Solution {
107+
public:
108+
string rearrangeString(string s, int k) {
109+
unordered_map<char, int> cnt;
110+
for (char c : s) ++cnt[c];
111+
priority_queue<pair<int, char>> pq;
112+
for (auto& [c, v] : cnt) pq.push({v, c});
113+
queue<pair<int, char>> q;
114+
string ans;
115+
while (!pq.empty()) {
116+
auto [v, c] = pq.top();
117+
pq.pop();
118+
ans += c;
119+
q.push({v - 1, c});
120+
if (q.size() >= k) {
121+
auto p = q.front();
122+
q.pop();
123+
if (p.first) {
124+
pq.push(p);
125+
}
126+
}
127+
}
128+
return ans.size() == s.size() ? ans : "";
129+
}
130+
};
131+
```
56132
133+
### **Go**
134+
135+
```go
136+
func rearrangeString(s string, k int) string {
137+
cnt := map[byte]int{}
138+
for i := range s {
139+
cnt[s[i]]++
140+
}
141+
pq := hp{}
142+
for c, v := range cnt {
143+
heap.Push(&pq, pair{v, c})
144+
}
145+
ans := []byte{}
146+
q := []pair{}
147+
for len(pq) > 0 {
148+
p := heap.Pop(&pq).(pair)
149+
v, c := p.v, p.c
150+
ans = append(ans, c)
151+
q = append(q, pair{v - 1, c})
152+
if len(q) >= k {
153+
p = q[0]
154+
q = q[1:]
155+
if p.v > 0 {
156+
heap.Push(&pq, p)
157+
}
158+
}
159+
}
160+
if len(ans) == len(s) {
161+
return string(ans)
162+
}
163+
return ""
164+
}
165+
166+
type pair struct {
167+
v int
168+
c byte
169+
}
170+
171+
type hp []pair
172+
173+
func (h hp) Len() int { return len(h) }
174+
func (h hp) Less(i, j int) bool {
175+
a, b := h[i], h[j]
176+
return a.v > b.v
177+
}
178+
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
179+
func (h *hp) Push(v interface{}) { *h = append(*h, v.(pair)) }
180+
func (h *hp) Pop() interface{} { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }
57181
```
58182

59183
### **...**
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public:
3+
string rearrangeString(string s, int k) {
4+
unordered_map<char, int> cnt;
5+
for (char c : s) ++cnt[c];
6+
priority_queue<pair<int, char>> pq;
7+
for (auto& [c, v] : cnt) pq.push({v, c});
8+
queue<pair<int, char>> q;
9+
string ans;
10+
while (!pq.empty()) {
11+
auto [v, c] = pq.top();
12+
pq.pop();
13+
ans += c;
14+
q.push({v - 1, c});
15+
if (q.size() >= k) {
16+
auto p = q.front();
17+
q.pop();
18+
if (p.first) {
19+
pq.push(p);
20+
}
21+
}
22+
}
23+
return ans.size() == s.size() ? ans : "";
24+
}
25+
};
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
func rearrangeString(s string, k int) string {
2+
cnt := map[byte]int{}
3+
for i := range s {
4+
cnt[s[i]]++
5+
}
6+
pq := hp{}
7+
for c, v := range cnt {
8+
heap.Push(&pq, pair{v, c})
9+
}
10+
ans := []byte{}
11+
q := []pair{}
12+
for len(pq) > 0 {
13+
p := heap.Pop(&pq).(pair)
14+
v, c := p.v, p.c
15+
ans = append(ans, c)
16+
q = append(q, pair{v - 1, c})
17+
if len(q) >= k {
18+
p = q[0]
19+
q = q[1:]
20+
if p.v > 0 {
21+
heap.Push(&pq, p)
22+
}
23+
}
24+
}
25+
if len(ans) == len(s) {
26+
return string(ans)
27+
}
28+
return ""
29+
}
30+
31+
type pair struct {
32+
v int
33+
c byte
34+
}
35+
36+
type hp []pair
37+
38+
func (h hp) Len() int { return len(h) }
39+
func (h hp) Less(i, j int) bool {
40+
a, b := h[i], h[j]
41+
return a.v > b.v
42+
}
43+
func (h hp) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
44+
func (h *hp) Push(v interface{}) { *h = append(*h, v.(pair)) }
45+
func (h *hp) Pop() interface{} { a := *h; v := a[len(a)-1]; *h = a[:len(a)-1]; return v }

0 commit comments

Comments
 (0)