当前位置:网站首页>[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
边栏推荐
- Zhongang Mining: it has inherent advantages to develop the characteristic chemical industry dominated by fluorine chemical industry
- [机缘参悟-35]:鬼谷子-飞箝篇-远程连接、远程控制与远程测试之术
- CKS CKA ckad change terminal to remote desktop
- CADD课程学习(3)-- 靶点药物相互作用
- 众昂矿业:发展以氟化工为主的特色化工产业具有先天优势
- Linux基础 —— CentOS7 离线安装 MySQL
- MT manager test skiing Adventure
- What is the relationship between modeling and later film and television?
- What is the difference between memory leak and memory overflow?
- 2022年危险化学品经营单位安全管理人员考试题及在线模拟考试
猜你喜欢
Distance measurement - Hamming distance
Zhao Fuquan: to ensure supply in the short term, we should build a safe, efficient and resilient supply chain in the long term
Jielizhi, production line assembly link [chapter]
2022年起重机司机(限桥式起重机)考试试题及模拟考试
The digital summit is popular, and city chain technology has triggered a new round of business transformation
Zero foundation tutorial of Internet of things development
软件架构的本质
距离度量 —— 汉明距离(Hamming Distance)
Istio, ebpf and rsocket Broker: in depth study of service grid
rviz打开后如何显示实时2D地图
随机推荐
Why is PHP called hypertext preprocessor
Matplotlib常用设置
CKS CKA ckad change terminal to remote desktop
Yunxin small class | common cognitive misunderstandings in IM and audio and video
What is mosaic?
CKS CKA ckad change terminal to remote desktop
Compare the version number [double pointer to intercept the string you want]
Win 10 mstsc connect RemoteApp
Aaai22 | structural tagging and interaction modeling: a "slim" network for graph classification
Daily three questions 6.29
flutter Unable to load asset: assets/images/888. png
The digital summit is popular, and city chain technology has triggered a new round of business transformation
物联网现状及未来发展趋势
What is the relationship between modeling and later film and television?
Force buckle 710 Random numbers in the blacklist
Stm32f030f4 drives tim1637 nixie tube chip
认识--Matplotlib
Use 3DMAX to make a chess piece
[micro service sentinel] sentinel integrates openfeign
Three development trends of enterprise application from the perspective of the third technological revolution