[原题链接](https://leetcode-cn.com/problems/length-of-last-word/solution/qian-duan-shi-tang-ti-jie-chao-hao-li-ji-9j6v/) ## 反向遍历 过滤掉末尾空格后,反向遍历字符串,并使用 count 计数,再次遇到空格时结束。 ```js const lengthOfLastWord = function(s) { if (s.length === 0) return 0 let count = 0 for (let i = s.length - 1; i >= 0; i--) { if (s.charAt(i) === ' ') { if (count === 0) continue break } count++ } return count } ``` - 时间复杂度:O(n) - 空间复杂度:O(1)