Why this Python code is wrong?


  • 0
    N

    I thought "a " should return 0 not 1 because after the space there is no word.

    class Solution:
        # @param s, a string
        # @return an integer
        def lengthOfLastWord(self, s):
            cnt=0
            for cha in s:
                cnt+=1
                if cha == ' ':
                    cnt=0
            return cnt

  • 1
    class Solution:
    # @param s, a string
    # @return an integer
    def lengthOfLastWord(self, s):
        
        ctr = 0 
        temp = 0
        for char in s:
            if char != " ":
                temp = temp + 1
                ctr = temp
            elif char == " ":
                temp = 0
                
        return ctr        
    

  • 0
    W

    Let's look at the note in this problem:

    Note: A word is defined as a character sequence consists of non-space characters only.
    

    Considering the example 'a ', the character after 'a' is None, but None is not a word according to the definition of 'word' in the note. So you should return the length of last word 'a'.


Log in to reply
 

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