zoukankan      html  css  js  c++  java
  • 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()会将这些空格都隔开为‘’。

  • 相关阅读:
    读写ini文件
    身份证号码验证正则表达式
    使用SubSonic生成数据访问层步骤
    MonoRail&ActiveRecord开发中的注意事项
    C#实现邮件发送的功能
    建立ASP.NET服务器控件
    操作身份验证
    看了几天C#了...人开始变得有点急躁
    关于正则表达式
    如何在多台电脑上同时安装Windows
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5468843.html
Copyright © 2011-2022 走看看