-
Notifications
You must be signed in to change notification settings - Fork 2
/
fan-zhuan-dan-ci-shun-xu-lcof.rs
50 lines (40 loc) · 1.21 KB
/
fan-zhuan-dan-ci-shun-xu-lcof.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#![allow(dead_code, unused, unused_variables, non_snake_case)]
fn main() {}
struct Solution;
impl Solution {
pub fn reverse_words(s: String) -> String {
if s.is_empty() {
return Default::default();
}
// 先去掉首位的空格
let mut s = s.trim().as_bytes();
let mut i = s.len() - 1;
let mut new = vec![];
while !s.is_empty() {
match s.last() {
Some(&x) if x == b' ' => s = &s[..s.len() - 1],
_ => {
let mut i = s.len() - 1;
while let Some(&x) = s.get(i) {
if x != b' ' {
if i == 0 {
break;
}
i -= 1;
} else {
break;
}
}
if i != 0 {
i += 1;
}
new.extend_from_slice(&s[i..]);
new.push(b' ');
s = &s[..i];
}
}
}
new.pop();
String::from_utf8(new).unwrap()
}
}