58. Length of Last Word
Given a string s
consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0
.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World" Output: 5
Example 2:
Input: s = " " Output: 0
Constraints:
1 <= s.length <= 104
s
consists of only English letters and spaces' '
.
Rust Solution
struct Solution;
impl Solution {
fn length_of_last_word(s: String) -> i32 {
if let Some(last) = s.split_whitespace().last() {
last.len() as i32
} else {
0
}
}
}
#[test]
fn test() {
assert_eq!(
Solution::length_of_last_word(String::from("Hello World")),
5
);
}
Having problems with this solution? Click here to submit an issue on github.