#逆向遍历
class Solution:
def lengthOfLastWord(self, s: str) -> int:
n = len(s)
index = n - 1
while s[index] == ' ':
index -= 1
word_len = 0
while index >= 0 and s[index] != ' ':
word_len += 1
index -= 1
return word_len
方法二:split方法
思路:用split方式剔除掉字符串中的空格 ' ',并以列表 s_list 形式存储。
思路更加简单,直接上代码!
#split方法
class Solution:
def lengthOfLastWord(self, s: str) -> int:
s_list = [i for i in s.split(' ') if i]
if not s_list:
return 0
return len(s_list[-1])