Given a string s
consisting of words and spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World" Output: 5 Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon " Output: 4 Explanation: The last word is "moon" with length 4.
Example 3:
Input: s = "luffy is still joyboy" Output: 6 Explanation: The last word is "joyboy" with length 6.
Constraints:
1 <= s.length <= 104
s
consists of only English letters and spaces ' '
.s
.This problem asks to find the length of the last word in a given string. A "word" is defined as a maximal sequence of non-space characters. The solution uses a two-pointer approach for efficient traversal.
Trim Trailing Spaces: We first remove any trailing spaces from the input string s
. This simplifies the logic by ensuring we don't encounter trailing spaces when searching for the last word. While not strictly necessary in all solutions, it makes the core logic cleaner.
Find the End of the Last Word: A pointer i
starts at the end of the string (or end of the trimmed string). It moves backward until it finds a non-space character. This marks the end of the last word.
Find the Beginning of the Last Word: A second pointer j
is initialized to the same position as i
. It moves backward until it encounters a space. This marks the position before the beginning of the last word.
Calculate Length: The length of the last word is simply the difference between the indices i
and j
(i - j
).
def lengthOfLastWord(s: str) -> int:
"""
Finds the length of the last word in a string.
Args:
s: The input string.
Returns:
The length of the last word.
"""
s = s.rstrip() #remove trailing spaces
if not s: #Handle empty string case
return 0
n = len(s)
i = n - 1
while i >= 0 and s[i] == ' ':
i -= 1
j = i
while j >= 0 and s[j] != ' ':
j -= 1
return i - j
This Python code directly implements the steps described above. Note the rstrip()
method efficiently removes trailing whitespace. The if not s
condition handles empty strings as a special case. Other language implementations would follow a very similar structure, adapting the string manipulation and looping constructs as needed for each language. The core logic remains the same.