javascript-leetcode icon indicating copy to clipboard operation
javascript-leetcode copied to clipboard

58. 最后一个单词的长度

Open Geekhyt opened this issue 4 years ago • 0 comments

原题链接

反向遍历

过滤掉末尾空格后,反向遍历字符串,并使用 count 计数,再次遇到空格时结束。

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)

Geekhyt avatar Sep 19 '21 02:09 Geekhyt