Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Geekhyt opened this issue Sep 19, 2021 · 0 comments
Open

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

Geekhyt opened this issue Sep 19, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Sep 19, 2021

原题链接

反向遍历

过滤掉末尾空格后,反向遍历字符串,并使用 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 Geekhyt added the 简单 label Sep 19, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant