Content-Length: 253421 | pFad | https://github.com/Geekhyt/javascript-leetcode/issues/74

87 58. 最后一个单词的长度 · Issue #74 · Geekhyt/javascript-leetcode · GitHub
Skip to content

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

@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









      ApplySandwichStrip

      pFad - (p)hone/(F)rame/(a)nonymizer/(d)eclutterfier!      Saves Data!


      --- a PPN by Garber Painting Akron. With Image Size Reduction included!

      Fetched URL: https://github.com/Geekhyt/javascript-leetcode/issues/74

      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy