美文网首页
[SwapLine]58. Length of Last Wor

[SwapLine]58. Length of Last Wor

作者: 野生小熊猫 | 来源:发表于2019-02-08 09:49 被阅读0次
    • 分类: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 Wor

          本文链接:https://www.haomeiwen.com/subject/ngmnsqtx.html