• 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.

    For example, 
    Given s = "Hello World",
    return 5.

    简单题,既然求最后一个单词的长度,则最好的方式是从后往前扫。先记录最后一个非空格的字符所在的位置。之后从这个位置再往前扫,求这之前倒数第一个空格所在的位置,这二者相减,就是最后一个单词的长度。

    另外主要考虑在给出的字符串中只有字符没有空格的情况,是否会出错。此时end所在的位置是单词最末端,start所在的位置为-1,所以依然正确,简单题注意细节。

    class Solution(object):
        def lengthOfLastWord(self, s):
            """
            :type s: str
            :rtype: int
            """
            if not s:
                return 0
            end = len(s) -1
            while end >-1 and s[end].isspace():
                end -= 1
            start = end 
            while start >-1 and not s[start].isspace():
                start -= 1
            return end - start 

    另外一种使用python string 方法的做法:

    class Solution(object):
        def lengthOfLastWord(self, s):
            """
            :type s: str
            :rtype: int
            """
            return 0 if len(s.split())==0 else len(s.split()[-1]) 

    但是需要注意的是,str.split()和str.split(' ') 的差别,str.split()会把连续的空格都去除,并且忽略首尾的空格,但是str.split()会将这些空格都隔开为‘’。

  • 相关阅读:
    3164 质因数分解
    codevs3249搭积木
    codevs 2964公共素数因数
    爱改名的小融1
    单链表基础练习
    并查集(union-find sets)
    string类中字符的大小写转换
    蒜头君学英语--set()练习
    打印锯齿矩阵
    堆积木
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5468843.html
Copyright © 2020-2023  润新知