An intuitive Python solution - O(n) 56ms


  • 0
    G
    class Solution:
        # @param {string} s
        # @return {integer}
        def lengthOfLastWord(self, s):
            length, i = 0, len(s) - 1
            while i >= 0:
                if s[i] == ' ':
                    if not length:
                        pass
                    else:
                        break
                else:
                    length += 1
    
                i -= 1
    
            return length

Log in to reply
 

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