Skip to content

Commit 43a6f65

Browse files
committed
feat: update rust solution to lcof problem: No.58 - |
面试题58 - I. 翻转单词顺序
1 parent 1f24920 commit 43a6f65

File tree

2 files changed

+64
-7
lines changed

2 files changed

+64
-7
lines changed

lcof/面试题58 - I. 翻转单词顺序/README.md

+63
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,8 @@ function reverseWords(s: string): string {
149149

150150
### **Rust**
151151

152+
传统:
153+
152154
```rust
153155
impl Solution {
154156
pub fn reverse_words(mut s: String) -> String {
@@ -163,6 +165,67 @@ impl Solution {
163165
}
164166
```
165167

168+
函数式:
169+
170+
```rust
171+
impl Solution {
172+
pub fn reverse_words(s: String) -> String {
173+
s.split(' ')
174+
.filter(|str| str != &"")
175+
.rev()
176+
.collect::<Vec<_>>()
177+
.join("")
178+
}
179+
}
180+
```
181+
182+
使用 `split_whitespace()`
183+
184+
```rust
185+
impl Solution {
186+
pub fn reverse_words(s: String) -> String {
187+
s.split_whitespace().rev().collect::<Vec<_>>().join(" ")
188+
}
189+
}
190+
```
191+
192+
双指针:
193+
194+
```rust
195+
impl Solution {
196+
pub fn reverse_words(mut s: String) -> String {
197+
s = s.trim().to_string();
198+
// 添加辅助空格,防止 usize 破界
199+
s.insert_str(0, " ");
200+
let chars = s.chars().collect::<Vec<char>>();
201+
let mut res = vec![];
202+
let mut l = chars.len() - 1;
203+
let mut r = chars.len() - 1;
204+
while l > 0 {
205+
while chars[l] == ' ' {
206+
if l == 0 {
207+
break;
208+
}
209+
l -= 1;
210+
}
211+
r = l;
212+
while chars[l] != ' ' {
213+
if l == 0 {
214+
break;
215+
}
216+
l -= 1;
217+
}
218+
let mut str = String::new();
219+
for i in l + 1..r + 1 {
220+
str.push(chars[i]);
221+
}
222+
res.push(str);
223+
}
224+
res.join(" ")
225+
}
226+
}
227+
```
228+
166229
### **...**
167230

168231
```
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,5 @@
11
impl Solution {
22
pub fn reverse_words(mut s: String) -> String {
3-
let mut res = s.trim().split(' ').rev().collect::<Vec<&str>>();
4-
for i in (0..res.len()).rev() {
5-
if res[i] == "" {
6-
res.remove(i);
7-
}
8-
}
9-
res.join(" ")
3+
s.split_whitespace().rev().collect::<Vec<_>>().join(" ")
104
}
115
}

0 commit comments

Comments
 (0)