LeetCode题解(1160):判断可由指定字母拼写的所有单词总长(Python)
发布日期:2021-06-29 19:55:29 浏览次数:3 分类:技术文章

本文共 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

转载地址:https://dataartist.blog.csdn.net/article/details/107108025 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:LeetCode题解(1170):比较字符串最小字母的出现频次(Python)
下一篇:LeetCode题解(1154):判断日期在一年中的第几天(Python)

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年05月03日 06时01分39秒