From ec7fc6a29ee01e77408ff3b630c79802f92c212d Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 21 Apr 2024 13:49:42 +0800 Subject: [PATCH] 20240421 Finished --- src/problem/mod.rs | 3 +- src/problem/p151_reverse_words_in_a_string.rs | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 src/problem/p151_reverse_words_in_a_string.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 0b07603..0360ce6 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -107,4 +107,5 @@ mod p238_product_of_array_except_self; mod p134_gas_station; mod p135_candy; mod p42_trapping_rain_water; -mod p58_length_of_last_word; \ No newline at end of file +mod p58_length_of_last_word; +mod p151_reverse_words_in_a_string; \ No newline at end of file diff --git a/src/problem/p151_reverse_words_in_a_string.rs b/src/problem/p151_reverse_words_in_a_string.rs new file mode 100644 index 0000000..fd5d83a --- /dev/null +++ b/src/problem/p151_reverse_words_in_a_string.rs @@ -0,0 +1,41 @@ +/** + * [151] Reverse Words in a String + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn reverse_words(s: String) -> String { + let mut words = Vec::new(); + + for word in s.split(' ') { + if word.len() != 0 { + words.push(word); + } + } + + let length = words.len(); + let mut result = String::from(words[length - 1]); + + for i in (0..length - 1).rev() { + result.push(' '); + result.push_str(words[i]); + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_151() { + assert_eq!("blue is sky the".to_owned(), Solution::reverse_words("the sky is blue".to_owned())); + } +}