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

 

posted on 2016-05-07 17:49  Sheryl Wang  阅读(150)  评论(0编辑  收藏  举报

导航