Sponsored
Sponsored
This approach involves trimming any trailing spaces from the string, splitting it into words using spaces as delimiters, and then simply returning the length of the last word in the resulting list of words.
Time Complexity: O(n), where n is the length of the string.
Space Complexity: O(1), no extra space is used besides counters.
1def length_of_last_word(s: str) -> int:
2 return len(s.strip().split()[-1])
3
4print(length_of_last_word("Hello World")) # Outputs 5
This Python solution trims the input string, splits it into words, and returns the length of the last word found.
The JavaScript approach involves navigating from the end of the string, avoiding spaces until the last word is fully counted.