One line Python solution


  • 13
    R
    def lengthOfLastWord(self, s):
        return len(s.rstrip(' ').split(' ')[-1])
    

    I know this is not the solution that the question wants. Just for fun.


  • 1
    H

    You should use regex to split for \n \t etc. However, this solution is not fun at all for a test:)


  • 4
    P
    def lengthOfLastWord(self, s):
        return 0 if len(s.split()) == 0 else len(s.split()[-1])

  • 0
    A

    I can't see the reason why this solution could pass the 'a ' test case....


  • 0
    X

    I have already understood


  • 5
    C

    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])

  • 0
    Z

    My answer:

        return max(map(len, s.split(' ')))

  • 0
    B

    return len(s.split()[-1]) if s.split() else 0


  • 0
    P

    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)))))
    

  • 0
    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])
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.