Skip to content

Commit 826ddef

Browse files
authored
feat: add solutions to lc problem: No.1592 (doocs#3883)
1 parent fd47409 commit 826ddef

File tree

7 files changed

+249
-175
lines changed

7 files changed

+249
-175
lines changed

solution/1500-1599/1592.Rearrange Spaces Between Words/README.md

Lines changed: 84 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,9 @@ tags:
7676

7777
### 方法一:字符串模拟
7878

79-
统计字符串 `text` 中的空格数,记为 `cnt`。将 `text` 按空格分割成字符串数组 `words`。然后计算相邻字符串之间需要拼接的空格数,进行拼接。最后将剩余的空格拼接在末尾。
79+
我们先统计字符串 $\textit{text}$ 中的空格数,记为 $\textit{spaces}$。将 $\textit{text}$ 按空格分割成字符串数组 $\textit{words}$。然后计算相邻字符串之间需要拼接的空格数,进行拼接。最后将剩余的空格拼接在末尾。
8080

81-
时间复杂度 $O(n)$,空间复杂度 $O(n)$,其中 $n$ 表示字符串 `text` 的长度。
81+
时间复杂度 $O(n)$,空间复杂度 $O(n)$,其中 $n$ 表示字符串 $\textit{text}$ 的长度。
8282

8383
<!-- tabs:start -->
8484

@@ -87,43 +87,90 @@ tags:
8787
```python
8888
class Solution:
8989
def reorderSpaces(self, text: str) -> str:
90-
cnt = text.count(' ')
90+
spaces = text.count(" ")
9191
words = text.split()
92-
m = len(words) - 1
93-
if m == 0:
94-
return words[0] + ' ' * cnt
95-
return (' ' * (cnt // m)).join(words) + ' ' * (cnt % m)
92+
if len(words) == 1:
93+
return words[0] + " " * spaces
94+
cnt, mod = divmod(spaces, len(words) - 1)
95+
return (" " * cnt).join(words) + " " * mod
9696
```
9797

9898
#### Java
9999

100100
```java
101101
class Solution {
102102
public String reorderSpaces(String text) {
103-
int cnt = 0;
103+
int spaces = 0;
104104
for (char c : text.toCharArray()) {
105105
if (c == ' ') {
106-
++cnt;
106+
++spaces;
107107
}
108108
}
109-
String[] words = text.split("\\s+");
110-
List<String> res = new ArrayList<>();
111-
for (String w : words) {
112-
if (!"".equals(w)) {
113-
res.add(w);
114-
}
109+
String[] words = text.trim().split("\\s+");
110+
if (words.length == 1) {
111+
return words[0] + " ".repeat(spaces);
115112
}
116-
int m = res.size() - 1;
117-
if (m == 0) {
118-
return res.get(0) + " ".repeat(cnt);
113+
int cnt = spaces / (words.length - 1);
114+
int mod = spaces % (words.length - 1);
115+
StringBuilder sb = new StringBuilder();
116+
for (int i = 0; i < words.length; ++i) {
117+
sb.append(words[i]);
118+
if (i < words.length - 1) {
119+
sb.append(" ".repeat(cnt));
120+
}
119121
}
120-
String ans = String.join(" ".repeat(cnt / m), res);
121-
ans += " ".repeat(cnt % m);
122-
return ans;
122+
sb.append(" ".repeat(mod));
123+
return sb.toString();
123124
}
124125
}
125126
```
126127

128+
#### C++
129+
130+
```cpp
131+
class Solution {
132+
public:
133+
string reorderSpaces(string text) {
134+
int spaces = ranges::count(text, ' ');
135+
auto words = split(text);
136+
137+
if (words.size() == 1) {
138+
return words[0] + string(spaces, ' ');
139+
}
140+
141+
int cnt = spaces / (words.size() - 1);
142+
int mod = spaces % (words.size() - 1);
143+
144+
string result = join(words, string(cnt, ' '));
145+
result += string(mod, ' ');
146+
147+
return result;
148+
}
149+
150+
private:
151+
vector<string> split(const string& text) {
152+
vector<string> words;
153+
istringstream stream(text);
154+
string word;
155+
while (stream >> word) {
156+
words.push_back(word);
157+
}
158+
return words;
159+
}
160+
161+
string join(const vector<string>& words, const string& separator) {
162+
ostringstream result;
163+
for (size_t i = 0; i < words.size(); ++i) {
164+
result << words[i];
165+
if (i < words.size() - 1) {
166+
result << separator;
167+
}
168+
}
169+
return result.str();
170+
}
171+
};
172+
```
173+
127174
#### Go
128175
129176
```go
@@ -142,54 +189,32 @@ func reorderSpaces(text string) string {
142189

143190
```ts
144191
function reorderSpaces(text: string): string {
145-
let count = 0;
146-
for (const c of text) {
147-
if (c === ' ') {
148-
count++;
149-
}
150-
}
151-
152-
const words = text.trim().split(/\s+/g);
153-
const n = words.length;
154-
if (n === 1) {
155-
return words.join('') + ''.padStart(count);
192+
const spaces = (text.match(/ /g) || []).length;
193+
const words = text.split(/\s+/).filter(Boolean);
194+
if (words.length === 1) {
195+
return words[0] + ' '.repeat(spaces);
156196
}
157-
158-
const rest = count % (words.length - 1);
159-
const per = (count - rest) / (words.length - 1);
160-
return words.join(''.padStart(per)) + ''.padStart(rest);
197+
const cnt = Math.floor(spaces / (words.length - 1));
198+
const mod = spaces % (words.length - 1);
199+
const result = words.join(' '.repeat(cnt));
200+
return result + ' '.repeat(mod);
161201
}
162202
```
163203

164204
#### Rust
165205

166206
```rust
167207
impl Solution {
168-
fn create_spaces(n: usize) -> String {
169-
let mut res = String::new();
170-
for _ in 0..n {
171-
res.push(' ');
172-
}
173-
res
174-
}
175-
176208
pub fn reorder_spaces(text: String) -> String {
177-
let count = {
178-
let mut res = 0;
179-
for c in text.as_bytes() {
180-
if c == &b' ' {
181-
res += 1;
182-
}
183-
}
184-
res
185-
};
186-
187-
let works = text.split_whitespace().collect::<Vec<&str>>();
188-
let n = works.len();
189-
if n == 1 {
190-
return works[0].to_string() + &Self::create_spaces(count);
209+
let spaces = text.chars().filter(|&c| c == ' ').count();
210+
let words: Vec<&str> = text.split_whitespace().collect();
211+
if words.len() == 1 {
212+
return format!("{}{}", words[0], " ".repeat(spaces));
191213
}
192-
works.join(&Self::create_spaces(count / (n - 1))) + &Self::create_spaces(count % (n - 1))
214+
let cnt = spaces / (words.len() - 1);
215+
let mod_spaces = spaces % (words.len() - 1);
216+
let result = words.join(&" ".repeat(cnt));
217+
result + &" ".repeat(mod_spaces)
193218
}
194219
}
195220
```

solution/1500-1599/1592.Rearrange Spaces Between Words/README_EN.md

Lines changed: 87 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,11 @@ tags:
5656

5757
<!-- solution:start -->
5858

59-
### Solution 1
59+
### Solution 1: String Simulation
60+
61+
First, we count the number of spaces in the string $\textit{text}$, denoted as $\textit{spaces}$. Then, we split $\textit{text}$ by spaces into an array of strings $\textit{words}$. Next, we calculate the number of spaces that need to be inserted between adjacent words and perform the concatenation. Finally, we append the remaining spaces to the end.
62+
63+
The time complexity is $O(n)$, and the space complexity is $O(n)$, where $n$ represents the length of the string $\textit{text}$.
6064

6165
<!-- tabs:start -->
6266

@@ -65,43 +69,90 @@ tags:
6569
```python
6670
class Solution:
6771
def reorderSpaces(self, text: str) -> str:
68-
cnt = text.count(' ')
72+
spaces = text.count(" ")
6973
words = text.split()
70-
m = len(words) - 1
71-
if m == 0:
72-
return words[0] + ' ' * cnt
73-
return (' ' * (cnt // m)).join(words) + ' ' * (cnt % m)
74+
if len(words) == 1:
75+
return words[0] + " " * spaces
76+
cnt, mod = divmod(spaces, len(words) - 1)
77+
return (" " * cnt).join(words) + " " * mod
7478
```
7579

7680
#### Java
7781

7882
```java
7983
class Solution {
8084
public String reorderSpaces(String text) {
81-
int cnt = 0;
85+
int spaces = 0;
8286
for (char c : text.toCharArray()) {
8387
if (c == ' ') {
84-
++cnt;
88+
++spaces;
8589
}
8690
}
87-
String[] words = text.split("\\s+");
88-
List<String> res = new ArrayList<>();
89-
for (String w : words) {
90-
if (!"".equals(w)) {
91-
res.add(w);
92-
}
91+
String[] words = text.trim().split("\\s+");
92+
if (words.length == 1) {
93+
return words[0] + " ".repeat(spaces);
9394
}
94-
int m = res.size() - 1;
95-
if (m == 0) {
96-
return res.get(0) + " ".repeat(cnt);
95+
int cnt = spaces / (words.length - 1);
96+
int mod = spaces % (words.length - 1);
97+
StringBuilder sb = new StringBuilder();
98+
for (int i = 0; i < words.length; ++i) {
99+
sb.append(words[i]);
100+
if (i < words.length - 1) {
101+
sb.append(" ".repeat(cnt));
102+
}
97103
}
98-
String ans = String.join(" ".repeat(cnt / m), res);
99-
ans += " ".repeat(cnt % m);
100-
return ans;
104+
sb.append(" ".repeat(mod));
105+
return sb.toString();
101106
}
102107
}
103108
```
104109

110+
#### C++
111+
112+
```cpp
113+
class Solution {
114+
public:
115+
string reorderSpaces(string text) {
116+
int spaces = ranges::count(text, ' ');
117+
auto words = split(text);
118+
119+
if (words.size() == 1) {
120+
return words[0] + string(spaces, ' ');
121+
}
122+
123+
int cnt = spaces / (words.size() - 1);
124+
int mod = spaces % (words.size() - 1);
125+
126+
string result = join(words, string(cnt, ' '));
127+
result += string(mod, ' ');
128+
129+
return result;
130+
}
131+
132+
private:
133+
vector<string> split(const string& text) {
134+
vector<string> words;
135+
istringstream stream(text);
136+
string word;
137+
while (stream >> word) {
138+
words.push_back(word);
139+
}
140+
return words;
141+
}
142+
143+
string join(const vector<string>& words, const string& separator) {
144+
ostringstream result;
145+
for (size_t i = 0; i < words.size(); ++i) {
146+
result << words[i];
147+
if (i < words.size() - 1) {
148+
result << separator;
149+
}
150+
}
151+
return result.str();
152+
}
153+
};
154+
```
155+
105156
#### Go
106157
107158
```go
@@ -120,54 +171,32 @@ func reorderSpaces(text string) string {
120171

121172
```ts
122173
function reorderSpaces(text: string): string {
123-
let count = 0;
124-
for (const c of text) {
125-
if (c === ' ') {
126-
count++;
127-
}
174+
const spaces = (text.match(/ /g) || []).length;
175+
const words = text.split(/\s+/).filter(Boolean);
176+
if (words.length === 1) {
177+
return words[0] + ' '.repeat(spaces);
128178
}
129-
130-
const words = text.trim().split(/\s+/g);
131-
const n = words.length;
132-
if (n === 1) {
133-
return words.join('') + ''.padStart(count);
134-
}
135-
136-
const rest = count % (words.length - 1);
137-
const per = (count - rest) / (words.length - 1);
138-
return words.join(''.padStart(per)) + ''.padStart(rest);
179+
const cnt = Math.floor(spaces / (words.length - 1));
180+
const mod = spaces % (words.length - 1);
181+
const result = words.join(' '.repeat(cnt));
182+
return result + ' '.repeat(mod);
139183
}
140184
```
141185

142186
#### Rust
143187

144188
```rust
145189
impl Solution {
146-
fn create_spaces(n: usize) -> String {
147-
let mut res = String::new();
148-
for _ in 0..n {
149-
res.push(' ');
150-
}
151-
res
152-
}
153-
154190
pub fn reorder_spaces(text: String) -> String {
155-
let count = {
156-
let mut res = 0;
157-
for c in text.as_bytes() {
158-
if c == &b' ' {
159-
res += 1;
160-
}
161-
}
162-
res
163-
};
164-
165-
let works = text.split_whitespace().collect::<Vec<&str>>();
166-
let n = works.len();
167-
if n == 1 {
168-
return works[0].to_string() + &Self::create_spaces(count);
191+
let spaces = text.chars().filter(|&c| c == ' ').count();
192+
let words: Vec<&str> = text.split_whitespace().collect();
193+
if words.len() == 1 {
194+
return format!("{}{}", words[0], " ".repeat(spaces));
169195
}
170-
works.join(&Self::create_spaces(count / (n - 1))) + &Self::create_spaces(count % (n - 1))
196+
let cnt = spaces / (words.len() - 1);
197+
let mod_spaces = spaces % (words.len() - 1);
198+
let result = words.join(&" ".repeat(cnt));
199+
result + &" ".repeat(mod_spaces)
171200
}
172201
}
173202
```

0 commit comments

Comments
 (0)