Python字符串问题

给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。
单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例 1:
输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为5。

目的是最后一个单词的长度,那么可以从后到前遍历减少时间复杂度

img

s = "Hello World"
i = -1  # 索引
word_len = 0
while True:  # 从后到前遍历
    if s[i] == " ":
        break   # 遇到空格说明已经获取到单词长度退出
    word_len += 1
    i -= 1   # 索引-1,向前遍历一位
print("最后一个单词长度:", word_len)

逐个字符计数,遇到空格归零就好

s = input()
cnt = 0
for i in s:
    if i == ' ':
        cnt = 0
    else:
        cnt += 1
print(cnt)

可以看下python参考手册中的 python- 字符串
s = input()
end_s = s.split(' ')[-1]
print(len(end_s))