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)