給定一個僅包含大小寫字母和空格 ' '
的字符串,返回其最後一個單詞的長度。
如果不存在最後一個單詞,請返回 0 。
說明:一個單詞是指由字母組成,但不包含任何空格的字符串。
示例:
輸入: "Hello World" 輸出: 5
這道題考察的情況較多,然後解法就是去掉首尾的空格再計數,我用正則一直沒成功,後面在學習學習正則,追加在後面正則的解法,現在先貼一篇別的解法
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
cnt, tail = 0, len(s) - 1
while tail >= 0 and s[tail] == ' ':
tail -= 1
while tail >= 0 and s[tail] != ' ':
cnt += 1
tail -= 1
return cnt