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())); + } +}