原题
https://leetcode.cn/problems/length-of-last-word/description/
思路
反向遍历
复杂度
时间:O(n)
空间:O(n)
Python代码
class Solution:
def lengthOfLastWord(self, s: str) -> int:
i = len(s) - 1
while i >= 0 and s[i] == ' ':
i -= 1
ans = 0
while i >= 0 and s[i] != ' ':
ans += 1
i -= 1
return ans
Go代码
func lengthOfLastWord(s string) int {
i := len(s) - 1
// 忽略右边空格
for i >= 0 && s[i] == ' ' {
i--
}
ans := 0
// 计算单词长度
for i >= 0 && s[i] != ' ' {
ans++
i--
}
return ans
}
最后一个单词的长度解析


被折叠的 条评论
为什么被折叠?



