LeetCode小白菜笔记[14]:Length of Last Word

LeetCode小白菜笔记[14]:Length of Last Word

58. Length of Last Word [easy]

题目如下:

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

这个题目比较简单,开始时错了,因为没有考虑最后一个单词后面还有空格的情况,题目要求这样的情况也有读出来最后单词长度。因此,设置一个hasword,对于已经有单词的空格才break,否则什么都不做,直接往前继续读入char,并且对非空格的char给length +1s。code 如下:

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        if len(s) == 0:
            return 0
        lenolast = 0
        hasword = False
        for i in range(1,len(s)+1):
            if s[-i] == " ":
                if hasword:
                    break
            else:
                hasword = True
                lenolast += 1
        return lenolast

结果33ms,45.50%。(没有鼠标截图不方便,从这个开始以后的截图没有啦)

2018年2月9日17:34:41

世界在雾中。——朴树 《猎户星座》

posted @ 2018-02-09 17:36  毛利小九郎  阅读(74)  评论(0编辑  收藏  举报