Open waker0086 opened 2 years ago
使用python中字符串的内置函数strip()去除字符串首尾空格,使用split()按照空格将字符串切分成单词数组,找到最后一个单词并计算其长度
使用strip()去除首尾空格 使用split()将字符串切分成单词数组 计算数组最后一个单词长度
时间复杂度分析: O(n)
空间复杂度分析: O(n)
def last_word_length(input()):
word_list = input().strip().split()
l = len(word_list[-1])
return l
去除字符串首尾空格,设置指针,从数组的末尾向数组头部移动,直至遇到空格或者遇到数组首位元素,此时指针移动距离即最后一个单词的长度
去掉首尾空格 指针从数组末尾开始移动,判断
def last_word_length(input()):
input_str = input().strip()
dis = 0
for i in range(len(input_str)-1, -1, -1): #从最后一个循环到第一个
if input_str[i] == ' ':
break
dis += 1
print(dis)
或
# def last_word_length(word):
# n = len(word)
# l = 0
# for i in range(-1, -n - 1, -1): #从最后一个循环到第一个
# if word[i] == ' ' and i > -n:
# break
# l += 1
# return l
# def last_word_length(word):
# n=len(word)
# for i in range(-1,-n-1,-1):
# if word[i] == ' ':
# break
# return abs(i)-1
此时不满足只有一个单词情况,即字符串中不存在空格,刚好遍历完整个字符串
不应该用i作为标准来计算长度,而是计算循环的次数,此处对于满足空格的轮次,直接退出整个循环,而不用计算 +1
https://www.runoob.com/python3/python3-loop.html
break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。
continue 语句被用来告诉 Python 跳过当前循环块中的剩余语句,然后继续进行下一轮循环。
else可以与循环搭配使用,看else与谁匹配,与for语句匹配,只有当内层循环没有break打断,且循环列表遍历完毕的情况下才执行else后面的语句。与while搭配使用,在while条件语句不满足的情况下执行 #28
while 中使用 break:
实例
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print('循环结束。')
输出结果为:
4 3 循环结束。
while 中使用 continue:
实例
n = 5
while n > 0:
n -= 1
if n == 2:
continue
print(n)
print('循环结束。')
输出结果为:
4 3 1 0 循环结束。
str.strip([chars]);
移除收尾空格
str2 = " Runoob "; # 去除首尾空格
print str2.strip();
输出
Runoob
移除字符串头尾指定的字符
str = "00000003210Runoob01230000000";
print str.strip( '0' ); # 去除首尾字符 0
输出
3210Runoob0123
只要头尾包含有指定字符序列中的字符就删除:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = "123abcrunoob321" print (str.strip( '12' )) # 字符序列为 12
输出
`3abcrunoob3`
https://www.runoob.com/python/att-string-split.html
Python split() 通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串
str.split(str="", num=string.count(str)).
参数
#!/usr/bin/python
# -*- coding: UTF-8 -*-
str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( ); # 以空格为分隔符,包含 \n
print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个
['Line1-abcdef', 'Line2-abc', 'Line4-abcd'] ['Line1-abcdef', '\nLine2-abc \nLine4-abcd']
#!/usr/bin/python
# -*- coding: UTF-8 -*-
txt = "Google#Runoob#Taobao#Facebook"
x = txt.split("#", 1)
print x
> ['Google', 'Runoob#Taobao#Facebook'] **#并不包括分隔符本身**
描述 计算字符串最后一个单词的长度,单词以空格隔开,字符串长度小于5000。(注:字符串末尾不以空格为结尾) 输入描述: 输入一行,代表要计算的字符串,非空,长度小于5000。
输出描述: 输出一个整数,表示输入字符串最后一个单词的长度。
https://www.nowcoder.com/practice/8c949ea5f36f422594b306a2300315da