leetcode_rust/
reverse_words_in_a_string_3.rs

1#![allow(dead_code)]
2
3pub fn reverse_words(s: String) -> String {
4    let words: Vec<&str> = s.split_whitespace().collect();
5    let mut res = String::new();
6    for word in words {
7        for c in word.chars().rev() {
8            res.push(c);
9        }
10        res.push(' ');
11    }
12
13    res.pop();
14    res
15}
16
17// in-place
18pub fn reverse_words2(s: String) -> String {
19    let mut words: Vec<Vec<u8>> = s.split_whitespace().map(|s| s.into()).collect();
20    for word in &mut words {
21        let mut i: i32 = 0;
22        let mut j: i32 = word.len() as i32 - 1;
23        while i <= j {
24            word.swap(i as usize, j as usize);
25            i += 1;
26            j -= 1;
27        }
28    }
29    words
30        .into_iter()
31        .map(|s| unsafe { String::from_utf8_unchecked(s) })
32        .collect::<Vec<String>>()
33        .join(" ")
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn test1() {
42        assert_eq!(
43            reverse_words("Let's take LeetCode contest".to_string()),
44            "s'teL ekat edoCteeL tsetnoc".to_string()
45        );
46    }
47
48    #[test]
49    fn test2() {
50        assert_eq!(
51            reverse_words2("Let's take LeetCode contest".to_string()),
52            "s'teL ekat edoCteeL tsetnoc".to_string()
53        );
54
55        assert_eq!(
56            reverse_words2("I love u".to_string()),
57            "I evol u".to_string()
58        );
59    }
60}