leetcode_rust/
reverse_words_in_a_string.rs

1#![allow(dead_code)]
2
3pub fn reverse_words(s: String) -> String {
4    let words: Vec<&str> = s.split(' ').collect();
5    let s = words
6        .into_iter()
7        .rev()
8        .fold(String::new(), |acc, x| match x.chars().nth(0) {
9            Some(x) if x.is_whitespace() => acc,
10            None => acc,
11            _ => acc + " " + x,
12        });
13    s.trim().to_string()
14}
15
16pub fn reverse_words2(s: String) -> String {
17    let s = s
18        .split_whitespace()
19        .into_iter()
20        .rev()
21        .collect::<Vec<&str>>();
22    s.join(" ")
23}
24
25#[cfg(test)]
26mod tests {
27    use super::*;
28
29    #[test]
30    fn test1() {
31        assert_eq!(
32            reverse_words("the sky is blue".to_string()),
33            "blue is sky the".to_string()
34        );
35
36        assert_eq!(
37            reverse_words("  hello world!  ".to_string()),
38            "world! hello".to_string()
39        );
40
41        assert_eq!(
42            reverse_words("a good   example".to_string()),
43            "example good a".to_string()
44        );
45    }
46
47    #[test]
48    fn test2() {
49        assert_eq!(
50            reverse_words2("the sky is blue".to_string()),
51            "blue is sky the".to_string()
52        );
53
54        assert_eq!(
55            reverse_words2("  hello world!  ".to_string()),
56            "world! hello".to_string()
57        );
58
59        assert_eq!(
60            reverse_words2("a good   example".to_string()),
61            "example good a".to_string()
62        );
63    }
64}