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