Leetcode: Length of last word
1 min readDec 28, 2016
Only trick here is to select the most efficient way of finding the last word
The below example solves the problem for sentences with space as delimiter. For any other delimiter replace the None with delimiter
Contant space and constant time complexity
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
words = s.rsplit(None, 1)
return len(words[-1]) if words else 0