leetcode python3 简单题58. Length of Last Word

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值