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
LeetCode:链接
从后往前遍历。首先找到字符串中第一不为’ ‘的值的坐标,该坐标即为最后一个Word的尾字母。然后继续遍历,如果碰到’ ‘,则遍历结束,否则,count++。最后返回count。
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
count = 0
end = len(s) - 1
'''从后往前遍历 直到找到不为空的字符'''
while end >= 0 and s[end]==' ':
end -= 1
'''继续从后往前遍历 直到找到下一个不为空的字符'''
while end >= 0 and s[end]!=' ':
end -= 1
count += 1
return count