瀏覽代碼

feat: reverse_words_in_a_string

Zhang Li 9 月之前
父節點
當前提交
3e470dc9f6
共有 2 個文件被更改,包括 23 次插入1 次删除
  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"));
+    }
+}