leetcode 解題 最後一個單詞的長度
阿新 • • 發佈:2018-12-11
給定一個僅包含大小寫字母和空格 ' '
的字串,返回其最後一個單詞的長度。
如果不存在最後一個單詞,請返回 0 。
說明:一個單詞是指由字母組成,但不包含任何空格的字串。
示例:
輸入: "Hello World" 輸出: 5
逆序迴圈,注意字串末尾出現空格的情況
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if(not s):
return 0
sLen = len(s)
index = sLen - 1
count = 0
while(index != -1):
if(s[index] == ' ' and count == 0):
index -= 1
else:
if(s[index] != ' '):
count += 1
else:
return count
index -= 1
return count