类型:字符串
-
- 最后一个单词的长度 💚
https://leetcode-cn.com/problems/length-of-last-word/
❓ 字符串 s 由若干个单词组成,单词间用空格分割,返回最后一个单词的长度。
💡 逆向一次遍历
由于我们要算最后一个单词的长度,直接从后往前遍历好了。
class Solution: def lengthOfLastWord(self, s: str) -> int: count = 0 for i in range(len(s) - 1, -1, -1): if s[i] != ' ': count += 1 elif count > 0: return count return count时间复杂度:O(n),空间复杂度:O(1)