My accepted Python solution


  • 2
    S
    class Solution:
        # @param s, a string
        # @return an integer
        def lengthOfLastWord(self, s):
            count = 0
            for i in range(len(s)-1,-1,-1):
                if s[i] != ' ':
                    while s[i] != ' ' and i >= 0:
                        count += 1
                        i -= 1
                    break
            return count

  • 2
    M

    I went with the more lazy option. Probably executes slower, but much simpler to write.

    class Solution:
        # @param s, a string
        # @return an integer
        def lengthOfLastWord(self, s):
            if len(s) == 0:
                return 0
            
            return len(s.strip().split(' ')[-1])

  • 0
    S

    Neat solution !

    But I am afraid if using Python functions like strip() and split() , which would reduce the LOC significantly, will go well with the interviewer.


  • 0
    F

    Mine has just one loop, if you could have a look:

    class Solution:
    # @param s, a string
    # @return an integer
    def lengthOfLastWord(self, s):
        count = 0
        lock = False
        if len(s) == 0: 
            return 0
        for i in range(len(s)-1,-1,-1):
            if s[i] != " ":
                count += 1
                lock = True
            if (s[i] == " " and lock) or (i == 0):
                return count
    

    I was using a lock to see if this the second times to see the space

    and BTW, if I used the xrange instead of range, this could be better, the runtime is 38ms


  • 0
    S

    Hi, I am new to LeetCode. I am wondering is it ok to use build-in function during interviews?


  • 0
    A

    Can someone take a look at my solution?

    class Solution:
        # @param {string} s
        # @return {integer}
        def lengthOfLastWord(self, s):
            for i in range(len(s)):
                length = 0
                if s[i] == ' ' and s[i+1] != ' ':
                    length = 1
                    while s[i+2] and s[i+2] != ' ':
                        length += 1
                    return length
    

    I think it should be accepted, but the system hints " Line 7: IndexError: string index out of range " .....


Log in to reply
 

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