给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
class Solution:
def lengthOfLastWord(self, s: str) -> int:
i = 0
j = 0
for ch in s: #找到字符串末尾空格开始的位置
if ch != ' ':
end_space_start = j
j += 1
if ' ' not in s[0:end_space_start+1]: #判断去掉末尾空格后字符串是否不包含空格(全为字母)
return len(s[0:end_space_start+1])
for ch in s[0:end_space_start]:
if ch == ' ': #判断最后一个字符串开始位置
last_str_start = i
i += 1
return len(s[last_str_start+1:end_space_start+1])
194

被折叠的 条评论
为什么被折叠?



