博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode题解(1160):判断可由指定字母拼写的所有单词总长(Python)
阅读量:1900 次
发布时间:2019-04-26

本文共 1425 字,大约阅读时间需要 4 分钟。

题目:(简单)

解法 时间复杂度 空间复杂度 执行用时
Ans 1 (Python) O ( N × K + C ) O(N×K+C) O(N×K+C) : K为单词平均长度,C为chars长度 O ( C ) O(C) O(C) : C为chars的长度 400ms (9.72%)
Ans 2 (Python) O ( N × K + C ) O(N×K+C) O(N×K+C) : K为单词平均长度,C为chars长度 O ( C ) O(C) O(C) : C为chars的长度 196ms (60.88%)
Ans 3 (Python) O ( N × K + C ) O(N×K+C) O(N×K+C) : K为单词平均长度,C为chars长度 O ( C ) O(C) O(C) : C为chars的长度 104ms (98.39%)

LeetCode的Python执行用时随缘,只要时间复杂度没有明显差异,执行用时一般都在同一个量级,仅作参考意义。

解法一(使用collections.Counter类):

def countCharacters(self, words: List[str], chars: str) -> int:    pattern = collections.Counter(chars)    ans = 0    for word in words:        count = pattern & collections.Counter(word)        if len(list(count.elements())) == len(word):            ans += len(word)    return ans

解法二(哈希表计数):

def countCharacters(self, words: List[str], chars: str) -> int:    pattern = collections.Counter(chars)    ans = 0    for word in words:        count = pattern.copy()        for c in word:            if c not in count or count[c] <= 0:                break            else:                count[c] -= 1        else:            ans += len(word)    return ans

解法三(更好的哈希表计数):

def countCharacters(self, words: List[str], chars: str) -> int:    pattern = collections.Counter(chars)    ans = 0    for word in words:        for c in word:            if c not in pattern or word.count(c) > pattern[c]:                break        else:            ans += len(word)    return ans

转载地址:http://yqgdf.baihongyu.com/

你可能感兴趣的文章
vs code编辑器 代码格式化 快捷键
查看>>
html 引入 JQuery
查看>>
Javascript 之 Array - entries()、every()、filter()
查看>>
ReferenceError: Unknown plugin component
查看>>
Cannot find module @babel/helper-module-imports
查看>>
vue 引入 element-ui 报 es2015 的错
查看>>
图片暴力压缩
查看>>
vue 插件 之 生成二维码 qrcodejs2
查看>>
javascript 之 获取毫秒时间戳
查看>>
python 环境搭建无坑
查看>>
python 配置web自动化测试框架 selenium
查看>>
python 自动化测试 selenium 框架 - 1
查看>>
html 导出 excel -- 1
查看>>
html 导出 excel 设置单元格文本格式 -- 2
查看>>
html 导出 excel 单元格合并 --3
查看>>
javascript 时间格式在iphone上的兼容问题 亲测有用 无坑点
查看>>
git 环境配置
查看>>
git 报 Incorrect username or password (access token)
查看>>
git 推送代码到远程仓库
查看>>
Android studio 安装 无坑
查看>>