My 36 ms Python solution


  • 7
    J
    def lengthOfLastWord(self, s):
        ls = len(s)
        # slow and fast pointers
        slow = -1
        # iterate over trailing spaces
        while slow >= -ls and s[slow] == ' ':
            slow-=1
        fast = slow
        # iterate over last word
        while fast >= -ls and s[fast] != ' ':
            fast-=1
        return slow - fast

  • 0
    Q
    This post is deleted!

  • 1
    Q
    def lengthOfLastWord(self, s):
        cnt = 0
        for v in reversed(s):
            if v.isspace():
                if cnt: break
            else: cnt += 1
        return cnt

  • 0
    B

    Nice. I had a very similar approach. I think mine is bottle necked by the reassigning of s in the first while loop.

    class Solution(object):
        def lengthOfLastWord(self, s):
            i = 0;
            while len(s) != 0 and s[-(i+1)] == ' ': 
                s = s[:-1]
            while i != len(s) and s[-(i+1)] != ' ': 
                i += 1
            return i
    

  • 1
    S

    Inspired by other solutions I saw around..

    def lengthOfLastWord(self, s):
        # (going backwards) find first non-space char
        for i in range(len(s) - 1, -2, -1):
            if i == -1 or s[i] != " ":
                break
        
        # keep going until a space or end of string
        for j in range(i, -2, -1):
            if j == -1 or s[j] == " ":
                return i - j
    

Log in to reply
 

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