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
.
自己写的~~
1 class Solution(object): 2 def lengthOfLastWord(self, s): 3 """ 4 :type s: str 5 :rtype: int 6 """ 7 if s=='': 8 return 0 9 10 mylist = s.split(' ') 11 for i in mylist[::-1]: 12 if i != '': 13 return len(i) 14 return 0
1 class Solution(object): 2 def lengthOfLastWord(self, s): 3 """ 4 :type s: str 5 :rtype: int 6 """ 7 return len(s.strip().split(' ')[-1])
s.strip()删除字符串开头和结尾的空格
s.strip(rm) 删除s字符串中开头、结尾处,位于 rm删除序列的字符
s.lstrip(rm) 删除s字符串中开头处,位于 rm删除序列的字符
s.rstrip(rm) 删除s字符串中结尾处,位于 rm删除序列的字符