NeetCode #8LC-58EasyArrays & Hashing
← Back to All Problems#8 · #58 · Length of Last Word(最后一个单词的长度)
📌 Problem Statement & Constraints
Given a string
s consisting of words and spaces, return the length of the last word. A word is a maximal substring of non-space characters. Constraints: 1 <= s.length <= 10^4; s contains only English letters and spaces.💡 Core Algorithmic Approaches
- Trailing spaces complicate a naive
split, so strip them first. - After stripping, the last word starts right after the final space. Use
rfind(' ')to locate it and return the length of the suffix. - If there is no space, the whole string is one word, so the answer is its length.
- Python one-liners:
len(s.split()[-1])orlen(s.rstrip().rsplit(' ', 1)[-1]).
💻 Benchmark Python3 Implementation
class Solution:
def lengthOfLastWord(self, s: str) -> int:
i = len(s) - 1
while i >= 0 and s[i] == " ": # skip trailing spaces
i -= 1
length = 0
while i >= 0 and s[i] != " ": # count the last word
length += 1
i -= 1
return length
# Concise equivalent
class Solution2:
def lengthOfLastWord(self, s: str) -> int:
return len(s.split()[-1])⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n) worst case (the string may be entirely spaces followed by one short word), but the scan starts from the end so it is usually much less.
💾 Space Complexity
O(1) for the pointer version; O(n) for split which materialises all words.
⚠️ Interview Pitfalls & Follow-ups
s.split(' ')[-1]: with explicit' 'as the separator, trailing spaces produce empty strings, so the last element may be"". Usesplit()with no argument (which collapses whitespace) or strip first.- Forgetting the trailing-space skip:
"a "should return 1, not 0. - Assuming exactly one space between words: the constraints allow multiple spaces.