Skip to content

Commit 4adfc6f

Browse files
committed
add solution
1 parent ed3b4db commit 4adfc6f

File tree

1 file changed

+25
-1
lines changed
  • reverse_words_in_a_string_iii/src

1 file changed

+25
-1
lines changed

reverse_words_in_a_string_iii/src/lib.rs

+25-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,31 @@ struct Solution {}
1212

1313
impl Solution {
1414
pub fn reverse_words(s: String) -> String {
15-
"".to_string()
15+
let mut i = 0;
16+
let chars = s.chars().collect::<Vec<char>>();
17+
let mut reversed = vec![];
18+
while i < s.len() {
19+
if chars[i] == ' ' {
20+
reversed.push(chars[i]);
21+
i += 1;
22+
continue;
23+
}
24+
let mut j = i;
25+
while j < s.len() && chars[j] != ' ' {
26+
j += 1;
27+
}
28+
let mut k = j - 1;
29+
loop {
30+
// push the char into the reversed vector until reach the index `i`
31+
reversed.push(chars[k]);
32+
if k == i {
33+
break;
34+
}
35+
k -= 1;
36+
}
37+
i = j;
38+
}
39+
reversed.iter().collect()
1640
}
1741
}
1842

0 commit comments

Comments
 (0)