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.
Clarifying Questions
- Input Format:
- Is the string guaranteed to contain at least one word?
- Yes, at least one word is present in the string.
- Whitespace Handling:
- How should leading or trailing whitespaces be handled?
- Leading and trailing whitespaces should be ignored. Only the length of the last word should be considered.
- Character Set:
- Can the string contain any special characters or should it only contain alphabetic characters?
- The problem specifies words and spaces, so let’s assume it can include other non-space characters too.
- Output:
- What should be returned if there are no non-space characters in the input string?
- This scenario does not occur based on the guarantee of at least one word in the string.
Strategy
- Trimming Whitespace:
- First, we will strip the trailing whitespace from the string to ensure trailing spaces are not considered.
- Splitting the String:
- We can then split the trimmed string into words based on spaces.
- The last element in this list of words will be our last word.
- Calculating the Length:
- Simply return the length of the last word in the list.
Code
Here is the implementation in Python:
def lengthOfLastWord(s: str) -> int:
# Strip the trailing whitespace if any
s = s.rstrip()
# Split the string based on spaces
words = s.split(' ')
# The last word will be the last element in the split list
last_word = words[-1]
# Return the length of the last word
return len(last_word)
Time Complexity
- Trimming: The
rstrip
method runs in O(n) time where n
is the length of the string.
- Splitting: The
split
method also runs in O(n) time.
- Length Calculation: The
len
function runs in O(1) time for a string.
Thus, the overall time complexity of the function is O(n), where n
is the length of the input string s
.
-
Got blindsided by a question you didn’t expect?
-
Spend too much time studying?
-
Or simply don’t have the time to go over all 3000 questions?