Skip to content

58. 最后一个单词的长度 #74

Open
@Geekhyt

Description

@Geekhyt

原题链接

反向遍历

过滤掉末尾空格后,反向遍历字符串,并使用 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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions