题目
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/search-insert-position
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题
class Solution:
def lengthOfLastWord(self, s: str) -> int:
s = s.strip() #去除前后空格
s = s.split(" ")[-1] #split()按空格分隔字符串 返回列表
return len(s)
结果:
看着代码短 但事实上还是费时间的
另一个方法
class Solution:
def lengthOfLastWord(self, s: str) -> int:
s = s.rstrip()
if s.count(' ') == 0:
return len(s)
x = 0
while True:
if s[-(x+1)] == ' ':
return x
x += 1
作者:xiao-sa-de-yuan-shuai
链接:https://leetcode-cn.com/problems/length-of-last-word/solution/cong-hou-bian-li-16ms-by-xiao-sa-de-yuan-shuai/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
结果: