zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    用到了yii2 hasMany() 方法,一对多关联
    jquery操作select标签change事件
    Yii2如何批量添加数据
    [bzoj1497][NOI2006]最大获利
    [bzoj]2962序列操作
    洛谷 P1350 车的放置
    洛谷 P1142 轰炸
    初级数论练习题
    洛谷 P3795 钟氏映射
    洛谷 2953 [USACO09OPEN]牛的数字游戏Cow Digit Game
  • 原文地址:https://www.cnblogs.com/morikokyuro/p/13256815.html
Copyright © 2011-2022 走看看