LeetCode每日一题(2021.9.21)【EASY】
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。
单词是指仅由字母组成、不包含任何空格字符的最大子字符串。
示例:
输入:s = “Hello World”
输出:5
输入:s = " fly me to the moon "
输出:4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/length-of-last-word
class Solution:
def lengthOfLastWord(self, s):
s = s.strip()
i,lenth = len(s)-1,0
while i > 0 :
if s[i] != " ":
i -= 1
else:
lenth = len(s)-1 - i
return lenth
if i == 0:
return len(s)
s = " fly me to the moon "
solution = Solution()
result = solution.lengthOfLastWord(s)
print("============")
print(result)
解法二
class Solution:
def lengthOfLastWord(self, s):
start,lenth = 0,0
s = s.strip()
while lenth == 0:
if " " in s[start:]:
start = s.index(" ",start) + 1
print(start)
else:
lenth = len(s)-start
return lenth
s = " fly me to the moon "
solution = Solution()
result = solution.lengthOfLastWord(s)
print("============")
print(result)
解法三
class Solution:
def lengthOfLastWord(self, s):
lenth = len(s.strip().split(" ")[-1])
return lenth
该博客介绍了如何解决LeetCode上的一个简单问题——求字符串中最后一个单词的长度。作者提供了三种不同的解法,分别通过迭代和字符串操作找到最后一个单词的长度。示例中给出了输入字符串flymetothemoon,解法正确返回了最后一个单词的长度4。
940

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



