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()会将这些空格都隔开为‘’。

  • 相关阅读:
    extjs__(grid Panel绑定数据)
    web项目中对post请求乱码处理
    lucene之Field属性的解释
    spring整合mybatis框架
    jasperreports实现pdf文档的生成
    ireport图形化界面生成pdf文档
    iText框架(生成pdf文档)
    spring配置问题
    动手实践PHP7的HashTable
    基于epoll实现一个IO多路复用的回声服务器
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5468843.html
Copyright © 2011-2022 走看看