题目:
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.
Example:
Input: "Hello World" Output: 5
我的解法:
def lengthOfLastWord(self, s):
list_filed = s.split(' ')
while '' in list_filed:
list_filed.remove('')
if not list_filed:
return 0
word = list_filed.pop()
return len(word)
参考
x = s.split()
return len(x[-1]) if len(x) > 0 else 0
s.split('') //错误
s.split() //正确,split默认为所有的空字符,包括空格、换行(\n)、制表符(\t)等
--------------新手刷题,仅用于自身记录,如有错误,欢迎指出---------------