topic:
You are given a string s, which consists of several words separated by some space characters before and after the words. Returns the length of the last word in a string.
A word is the largest substring that consists only of letters and does not contain any space characters.
Example 1:
输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为5。
Example 2:
输入:s = " fly me to the moon "
输出:4
解释:最后一个单词是“moon”,长度为4。
Example 3:
输入:s = "luffy is still joyboy"
输出:6
解释:最后一个单词是长度为6的“joyboy”。
answer:
As can be seen from Example 2, there may be spaces at the end of the string.
class Solution:
def lengthOfLastWord(self, s: str) -> int:
i, count = len(s) - 1, 0
while i >= 0 and s[i] == ' ':
i -= 1
while i >= 0:
if s[i] == ' ':return count
count += 1
i -= 1
return count
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(s.split()[-1])
# 还有一种方法就是使用 split() 函数
# split() 通过指定分隔符对字符串进行切片,如果第二个参数 num 有指定值,则分割为 num+1 个子字符串。
# split("x", 2)则表示以x为分隔符,将字符串分成3个,从前往后分割依次
# 在此题中,分割完再以[-1]取最后一个字符串再计算长度