当前位置:网站首页>[LeetCode] 最后一个单词的长度【58】
[LeetCode] 最后一个单词的长度【58】
2022-07-01 22:55:00 【山茶花开时。】
问题: 给你一个字符串s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度(单词是指仅由字母组成、不包含任何空格字符的最大子字符串)
示例1
输入: s = "Hello World"
输出: 5
解释: 最后一个单词是“World”,长度为5
示例2
输入: s = " fly me to the moon "
输出: 4
解释: 最后一个单词是“moon”,长度为4
示例3
输入: s = "luffy is still joyboy"
输出: 6
解释: 最后一个单词是长度为6的“joyboy”
# 解法1
def lengthOfLastWord(s):
# 删除字符串两端的空格
s = s.strip(" ")
arr = s.split(" ")
lastWord = arr[-1]
res = len(lastWord)
return res
# 解法2
def lengthOfLastWord(s):
res = []
new_s = s.strip()
new_s = new_s[::-1]
for i in new_s:
if i != ' ':
res.append(i)
else:
break
return len(res)
lengthOfLastWord("Hello World") # 5
lengthOfLastWord(" fly me to the moon ") # 4
lengthOfLastWord("luffy is still joyboy") # 6
边栏推荐
- 为什么PHP叫超文本预处理器
- CKS CKA CKAD 将终端更改为远程桌面
- Convergence and disposal suggestions of some Internet exposure surfaces
- 共享电商的背后: 共创、共生、共享、共富,共赢的共富精神
- Compare the version number [double pointer to intercept the string you want]
- 【Swoole系列1】在Swoole的世界中,你将学习到什么?
- [MySQL] index creation, viewing and deletion
- 【微服务|Sentinel】@SentinelResource详解
- Understanding threads
- mysql ---- Oracle中的rownum转换成MySQL
猜你喜欢
2022年R1快开门式压力容器操作考题及答案
Jielizhi, production line assembly link [chapter]
Three development trends of enterprise application from the perspective of the third technological revolution
What is mosaic?
Istio、eBPF 和 RSocket Broker:深入研究服务网格
认识--Matplotlib
CKS CKA CKAD 将终端更改为远程桌面
[kotlin third party] coil koltin collaboration picture loading library coil glide like picture loading third party
Matplotlib常用图表
Jerry's burning of upper version materials requires [chapter]
随机推荐
Notes on problems - /usr/bin/perl is needed by mysql-server-5.1.73-1 glibc23.x86_ sixty-four
Development trend and future direction of neural network Internet of things
2022 examination questions and online simulation examination for safety management personnel of hazardous chemical business units
[applet] realize the left and right [sliding] list through the scroll view component
Microservice stability management
flutter Unable to load asset: assets/images/888.png
Jerry's records are powered by Vbat with a power supply voltage of 4.2V [chapter]
Leetcode(34)——在排序数组中查找元素的第一个和最后一个位置
Convergence and disposal suggestions of some Internet exposure surfaces
CKS CKA ckad change terminal to remote desktop
Matplotlib常用设置
from pip._internal.cli.main import main ModuleNotFoundError: No module named ‘pip‘
Which securities company is better and which is safer to open a securities account
CKS CKA CKAD 将终端更改为远程桌面
[micro service sentinel] sentinelresourceaspect details
Zero foundation tutorial of Internet of things development
MT manager test skiing Adventure
问题随记 —— /usr/bin/perl is needed by MySQL-server-5.1.73-1.glibc23.x86_64
mysql ---- Oracle中的rownum转换成MySQL
The digital summit is popular, and city chain technology has triggered a new round of business transformation