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.
思路:
首先就是找到最后一個(gè)單詞尖淘。首先考慮的就是使用split()函數(shù)得到一個(gè)list,然后取最后一個(gè),調(diào)用len函數(shù)剪芍。考慮到字符串為空或者全部由空白字符組成界阁。所以要對(duì)s.split()進(jìn)行非空判斷令漂。
#!/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)