[SwapLine]58. Length of Last Word

  • 分类:SwapLine
  • 时间复杂度: O(n)

58. Length of Last Word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

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

Example:

Input: "Hello World"
Output: 5

代码:

方法:

class Solution:
    def lengthOfLastWord(self, s: 'str') -> 'int':
        if s=='' or len(s)==0:
            return 0
        
        i=1
        while i<=len(s) and s[-i]==" ":
            i+=1        
        if i==len(s)+1:
            return 0
        
        j=i
        while(i<=len(s)):
            if s[-i]==" ":
                return i-j
            else:
                i+=1
        
        return i-j

讨论:

1.看上去很简单,其实做了我半个小时= 。=
2.边界一定要注意

你可能感兴趣的:([SwapLine]58. Length of Last Word)