1.编辑器
我使用的是win10+vscode+leetcode+python3
环境配置参见我的博客:
链接
2.第五十八题
(1)题目
英文:
Given a string s consists of upper/lower-case alphabets and empty space characters ’ ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.
If the last word does not exist, return 0.
Note: A word is defined as a maximal substring consisting of non-space characters only.
中文:
给定一个仅包含大小写字母和空格 ’ ’ 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/length-of-last-word
(2)解法
① (耗时:44ms,内存:13.6M)
class Solution:
def lengthOfLastWord(self, s: str) -> int:
split_s = s.split()
if split_s:
return len(split_s[-1])
else:
return 0
注意:
1.s.split(’’)会提示空的分割符,应该用’ '或者不用任何字符来表示空格 。
② 分情况讨论(耗时:36ms,内存:13.7M)
class Solution:
def lengthOfLastWord(self, s: str) -> int:
count = 0
flag = 0
for indx in range(len(s)-1, -1, -1):
if s[indx]==' ' and flag==1 :
return count
if s[indx]!=' ':
count+=1
flag=1
if count==len(s):
return count
if indx==0 and s[0]!=' ':
return count
return 0
注意:
1.range(len(s)-1, -1, -1)是[len(s)-1, …, 0]。
2.分几种情况:
从右往左看
① s中全是空格,则直接输出0
② 若第一个为空格,第二个后全为字母,则一直count+=1,直到indx到了最前面的0,return总的计数值
③ 如果s全是字母,则当count==len(s):时,return总的计数值
④ 如果第一个开始为字母,直到碰到空格,计数其间的字母个数
3.当出现第一个字母时,flag从0变为了1,所以下面只要出现空格,就可以return了
当然了,解法②还有更简单的写法:(耗时:44ms,内存:13.6M)
class Solution:
def lengthOfLastWord(self, s: str) -> int:
count = 0
for indx in range(len(s) - 1, -1, -1):
if s[indx] != " ":
while indx >= 0 and s[indx] != " ":
count += 1
indx -= 1
break
return count