美文网首页
[LeetCode][Python]58. Length of

[LeetCode][Python]58. Length of

作者: bluescorpio | 来源:发表于2017-06-11 16:50 被阅读126次

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.

思路:

首先就是找到最后一个单词。首先考虑的就是使用split()函数得到一个list,然后取最后一个,调用len函数。考虑到字符串为空或者全部由空白字符组成。所以要对s.split()进行非空判断。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s or not s.split():
            return 0
        return len(s.split()[-1])
    def lengthOfLastWord2(self,s):
        return 0 if len(s.split()) == 0 else len(s.split()[-1])

if __name__ == '__main__':
    sol = Solution()
    s = "hello world"
    print sol.lengthOfLastWord(s)

    s = "hello"
    print sol.lengthOfLastWord(s)
    print sol.lengthOfLastWord2(s)

    s = " "
    print sol.lengthOfLastWord(s)
    print sol.lengthOfLastWord2(s)


相关文章

网友评论

      本文标题:[LeetCode][Python]58. Length of

      本文链接:https://www.haomeiwen.com/subject/zowhqxtx.html