def lengthOfLastWord(self, s): return len(s.rstrip(' ').split(' ')[-1])
I know this is not the solution that the question wants. Just for fun.
You should use regex to split for \n \t etc. However, this solution is not fun at all for a test:)
def lengthOfLastWord(self, s): return 0 if len(s.split()) == 0 else len(s.split()[-1])
similar to yours, my solution. 40 ms, beats 88.34%.
class Solution(object): def lengthOfLastWord(self, s): """ :type s: str :rtype: int """ return len(s.strip().split(' ')[-1])
more complex one line solution using iterator
no extra string or list generated during execution
from itertools import * class Solution(object): def lengthOfLastWord(self, s): return sum(1 for _ in takewhile(str.isalpha, dropwhile(str.isspace, imap(str, reversed(s)))))
I mean, for python, it is the way to solve for sure, and during interview I believe interviewer should assume that if we use python, this solution would appear. And all other ways to solve this problem with python is not obey the meaning of using python.
BTW, here is my solution with one line, beat 98%:
return 0 if not s.split() else len(s.split()[-1])
Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.