Two python solutions (two pointers and split)


  • 2
    F

    Using split is simple in python, but two pointer solution saves memory.

    Split Version

    class Solution(object):
        def lengthOfLastWord(self, s):
            """
            :type s: str
            :rtype: int
            """
            l = s.split()
            if len(l) == 0: return 0
            else: return len(l[-1])
    

    Two Pointer Version (use a boolean variable to indicate whether we should update the length)

    class Solution(object):
        def lengthOfLastWord(self, s):
            """
            :type s: str
            :rtype: int
            """
            start, res = 0, 0
            calc = True
            s += " "
            for i in xrange(len(s)):
                cur = s[i]
                if cur == ' ' and calc: 
                    res = i-start
                    calc = False
                elif cur != ' ' and not calc:
                    start = i
                    calc = True
            return res

Log in to reply
 

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