Leetcode #58, https://leetcode.com/problems/length-of-last-word/
出题人的本意不是要用Python了。因为Python专门擅长干这个。
class Solution:
def lengthOfLastWord(self, s: str) -> int:
k = s.strip().split(' ')
if len(k) > 0:
return len(k[len(k)-1])
else:
return 0
其实就是看你怎么实现strip和split函数了。
反过来直接数也是可以的。
class Solution:
def lengthOfLastWord(self, s: str) -> int:
startCounting = False
count = 0
for x in s[-1::-1]:
if x ==' ':
if not startCounting:
continue
else:
break
else:
count += 1
startCounting = True
return count
也可以从前面开始数,个人认为会比较慢。因为数了好多不需要的。从后面数应该是最优的。
参见Michelle小梦想家的https://www.youtube.com/watch?v=L1Gm5SWFDhs&list=PL2rWx9cCzU84eBz9Xfp9Rah5Fexq5yrh8&index=17
class Solution:
def lengthOfLastWord(self, s: str) -> int:
retCount = 0
count = 0 # 这个trick挺好,用一个变量来保存目前数到的word长度,但这不一定是最后一个。retCount才是最后一个
for x in s:
if x ==' ':
count = 0
else:
count += 1
retCount = count #这种ping-pong式挺好,只有真的字符才算数。
return retCount