From f84124d26c8814889264fda920ff8d3a94549e3e Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sat, 20 Apr 2024 10:50:10 +0800 Subject: [PATCH] 20240420 Finished --- src/problem/mod.rs | 3 ++- src/problem/p58_length_of_last_word.rs | 35 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 src/problem/p58_length_of_last_word.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 0ec7f6b..0b07603 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -106,4 +106,5 @@ mod p380_insert_delete_getrandom_o1; mod p238_product_of_array_except_self; mod p134_gas_station; mod p135_candy; -mod p42_trapping_rain_water; \ No newline at end of file +mod p42_trapping_rain_water; +mod p58_length_of_last_word; \ No newline at end of file diff --git a/src/problem/p58_length_of_last_word.rs b/src/problem/p58_length_of_last_word.rs new file mode 100644 index 0000000..e24a4fa --- /dev/null +++ b/src/problem/p58_length_of_last_word.rs @@ -0,0 +1,35 @@ +/** + * [58] Length of Last Word + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn length_of_last_word(s: String) -> i32 { + let words : Vec<&str> = s.split(' ').collect(); + + for word in words.iter().rev() { + if word.len() != 0 { + return word.len() as i32; + } + } + + 0 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_58() { + assert_eq!(5, Solution::length_of_last_word("Hello World".to_owned())); + assert_eq!(4, Solution::length_of_last_word(" fly me to the moon ".to_owned())); + assert_eq!(6, Solution::length_of_last_word("luffy is still joyboy".to_owned())); + } +}