Python solution with O(n) time and O(1) space


  • 2
    C
    class Solution:
        # @param {string} s
        # @return {integer}
        def lengthOfLastWord(self, s):
            c = 0
            for i in xrange(len(s) -  1, -1, -1):
                # If we haven't seen any character, continue.
                if s[i] == ' ' and c == 0:
                    continue
                # We have seen at least one character and the word ends now.
                elif s[i] == ' ':
                    return c
                else:
                    c += 1
            return c

Log in to reply
 

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