Description:
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
解题思路:
看到这道题,我就感觉这道题能用一行Python代码解决。
1. 用split()将字符串分为单词的列表
2. 返回单词列表的最后一项(下标-1)的单词的长度(len())
特殊情况:若字符串为空或全为空格,则返回0。
Solution:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
return len(s.split()[-1]) if s.split() else 0
分析:
这道题虽然比较简单,但能运用Python语言的许多特性。
实质上,在这个一行解中,s被split了两次。若不追求一行解,则应用一个变量储存s.split()的结果。
评测结果: