58. Length of Last Word Easy

@problem@discussion
#String



1/**
2 * [58] Length of Last Word
3 *
4 * Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
5 * A word is a maximal substring consisting of non-space characters only.
6 *  
7 * Example 1:
8 *
9 * Input: s = "Hello World"
10 * Output: 5
11 * Explanation: The last word is "World" with length 5.
12 *
13 * Example 2:
14 *
15 * Input: s = "   fly me   to   the moon  "
16 * Output: 4
17 * Explanation: The last word is "moon" with length 4.
18 *
19 * Example 3:
20 *
21 * Input: s = "luffy is still joyboy"
22 * Output: 6
23 * Explanation: The last word is "joyboy" with length 6.
24 *
25 *  
26 * Constraints:
27 *
28 * 1 <= s.length <= 10^4
29 * s consists of only English letters and spaces ' '.
30 * There will be at least one word in s.
31 *
32 */
33pub struct Solution {}
34
35// problem: https://leetcode.com/problems/length-of-last-word/
36// discuss: https://leetcode.com/problems/length-of-last-word/discuss/?currentPage=1&orderBy=most_votes&query=
37
38// submission codes start here
39
40impl Solution {
41    pub fn length_of_last_word(s: String) -> i32 {
42        let mut flag = false;
43        let mut end = 0;
44        let mut start = s.len();
45        for (i, c) in s.chars().rev().enumerate() {
46            if !flag && c != ' ' {
47                flag = true;
48                end = i;
49            }
50
51            if flag && start == s.len() && c == ' ' {
52                start = i;
53            }
54        }
55        (start - end) as i32
56    }
57}
58
59// submission codes end
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_58() {
67        assert_eq!(
68            Solution::length_of_last_word("   fly me   to   the moon  ".to_owned()),
69            4
70        );
71        assert_eq!(
72            Solution::length_of_last_word("".to_owned()),
73            0
74        );
75        assert_eq!(
76            Solution::length_of_last_word("a".to_owned()),
77            1
78        );
79    }
80}
81


Back
© 2025 bowen.ge All Rights Reserved.