[SwapLine]58. Length of Last Wor

2019-02-08  本文已影响0人  野生小熊猫

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.边界一定要注意

上一篇下一篇

猜你喜欢

热点阅读