leetcode with python:58. Length of Last Word

题目:

Given a string s consisting of words and spaces, return the length of the last word in the string.

A word is a maximal substring consisting of non-space characters only.

给定一个字串,回传最后一个单字的长度
ex:input:"Hello World"=>output: 5
Explanation:The last word is "World" with length 5.

这题用简单的字串操作可以很简短

class Solution:    def lengthOfLastWord(self, s: str) -> int:        s=s.split()        return len(s[-1])

用split将里面单字化作阵列
然后回传最后一项得长度即可
最后执行时间28ms(faster than 95.93%)

当然,我们还是得用一下正当一点的解法,不要这样蒙混过关

class Solution:    def lengthOfLastWord(self, s: str) -> int:        if " " not in s: #若无空格该单字即为最后一项单字            return len(s)                    i=len(s)-1        ans=0        while s[i]==" ":            i=i-1        while i>=0 and s[i]!=" ":            ans=ans+1            i=i-1        return ans

我们从字串后往前看,找到第一个非空格字元(即最后一个单字的最后一个字)
由此开始算字元长度,直到遇到" "或index值超出範围
此时长度即为最后一个单字的长度
最后执行时间33ms(faster than 86.27%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章