58.最后一个单词的长度
给你一个字符串
s
,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。单词 是指仅由字母组成、不包含任何空格字符的最大子字符串。
解答①
def lengthOfLastWord(s): arr = s.split() res = [] for i in arr: res.append(len(i)) return res.pop() res = lengthOfLastWord(" fly me to the moon ") print(res)
注意:s.split() 与 s.split(" ")返回结果的区别
string = " hello world python " arr1 = string.split() arr2 = string.split(" ") print(arr1) print(arr2)
结果
['hello', 'world', 'python'] ['', 'hello', 'world', 'python', '']
解答②
def lengthOfLastWord(s): s = s.strip(' ') print(s) print(s.split(' ')) L = s.split(' ')[-1] print(L) return len(L) print(lengthOfLastWord(" hello world python Java "))
注意:s.strip()方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
也可以直接: return len(s.rstrip().split(" ")[-1])
官方解答
思想:反向遍历
题目要求得到字符串中最后一个单词的长度,可以反向遍历字符串,寻找最后一个单词并计算其长度。
由于字符串中至少存在一个单词,因此字符串中一定有字母。首先找到字符串中的最后一个字母,该字母即为最后一个单词的最后一个字母。
从最后一个字母开始继续反向遍历字符串,直到遇到空格或者到达字符串的起始位置。遍历到的每个字母都是最后一个单词中的字母,因此遍历到的字母数量即为最后一个单词的长度。
def lengthOfLastWordD(s): index = len(s) - 1 #当字符串后边有空格时,指针前移,直到指向最后一个单词最后一个字母 while s[index] == ' ': index -= 1 wordLength = 0 #当字符串没有遍历完并且当前字符不是空格时 while index >= 0 and s[index] != ' ': #当前是字母,长度加1 wordLength +=1 #指针接着向前遍历 index -=1 return wordLength print(lengthOfLastWordD(" fly me to the moon "))
复杂度
时间复杂度:O(n),其中 n 是字符串的长度。最多需要反向遍历字符串一次。
空间复杂度:O(1)。