Skip to main content

58. 最后一个单词的长度 [easy]

58. 最后一个单词的长度 [easy]

https://leetcode-cn.com/problems/length-of-last-word/

给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。

如果不存在最后一个单词,请返回 0 。

说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。

示例:

输入: "Hello World"
输出: 5

通过次数108,221 | 提交次数323,308

Second Try

2020-07-24

倒序遍历,明显会快一些。

class Solution:
def lengthOfLastWord(self, s: str) -> int:

count = 0
for i in range(len(s) - 1, -1, -1):
if s[i] == " ":
if count == 0:
continue
return count
count += 1
return count
  • 执行用时:48 ms, 在所有 Python3 提交中击败了18.70%的用户
  • 内存消耗:13.5 MB, 在所有 Python3 提交中击败了5.26%的用户
  • speed up version

把遍历从range(len(s) - 1, -1, -1)变成reversed(range(len(s))),速度竟然变成前排5%,太诡异了。

额,又测试了一遍,发现只是随机波动,变成倒数10%了。。。

class Solution:
def lengthOfLastWord(self, s: str) -> int:

count = 0
for i in reversed(range(len(s))):
if s[i] == " ":
if count == 0:
continue
return count
count += 1
return count
  • 执行用时:32 ms, 在所有 Python3 提交中击败了96.17%的用户
  • 内存消耗:13.7 MB, 在所有 Python3 提交中击败了5.26%的用户

First Try

2020-07-24

主要是"a "竟然返回1,而不是0,因此贡献了一次错误提交。。。

class Solution:
def lengthOfLastWord(self, s: str) -> int:
# 搞笑咯,竟然有"a "这种测试案例,然后返回1。
start = 0
restart = False
for c in s:
if c == " ":
restart = True
else:
if restart:
start = 1
restart = False
else:
start += 1
return start
  • 执行用时:40 ms, 在所有 Python3 提交中击败了67.30%的用户
  • 内存消耗:13.6 MB, 在所有 Python3 提交中击败了5.26%的用户