Browse Source

feat: reverse_words_in_a_string

Zhang Li 11 months ago
parent
commit
3e470dc9f6
2 changed files with 23 additions and 1 deletions
  1. 2 1
      src/solutions/str/mod.rs
  2. 21 0
      src/solutions/str/reverse_words_in_a_string.rs

+ 2 - 1
src/solutions/str/mod.rs

@@ -2,4 +2,5 @@ mod multiply_strings;
 mod strstr;
 mod minimum_window_substring;
 mod string_to_integer;
-mod valid_palindrome;
+mod valid_palindrome;
+mod reverse_words_in_a_string;

+ 21 - 0
src/solutions/str/reverse_words_in_a_string.rs

@@ -0,0 +1,21 @@
+struct Solution;
+
+impl Solution {
+    pub fn reverse_words(s: String) -> String {
+        s.split_whitespace().rev().collect::<Vec<&str>>().join(" ")
+
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn test_reverse_words() {
+        let s = String::from("a good   example");
+
+        let res = Solution::reverse_words(s);
+        assert_eq!(res, String::from( "example good a"));
+    }
+}