LeetCode-拼写单词

题目描述:

给你一份『词汇表』(字符串数组) words 和一张『字母表』(字符串) chars。

假如你可以用 chars 中的『字母』(字符)拼写出 words 中的某个『单词』(字符串),那么我们就认为你掌握了这个单词。

注意:每次拼写时,chars 中的每个字母都只能用一次。

返回词汇表 words 中你掌握的所有单词的 长度之和

示例:

输入:words = ["cat","bt","hat","tree"], chars = "atach"
输出:6
解释: 
可以形成字符串 "cat" 和 "hat",所以答案是 3 + 3 = 6。

输入:words = ["hello","world","leetcode"], chars = "welldonehoneyr"
输出:10
解释:
可以形成字符串 "hello" 和 "world",所以答案是 5 + 5 = 10。

 

解题思路:

使用哈希表的形式解题。(1)hash表的访问速度快。(2)先使用hash表存储 chars 中的字母出现的次数,再循环获得 words 列表中各个字符串中字符出现的次数,分别组成新的hash表,并将此表与 chars 中获得的hash表进行对比,如果 words 中的各个hash表与 chars 中获得的hash表的元素及出现的次数一致或小于后者出现的次数,则表明 words 中的这个字符串已经掌握,将该字符串的长度存储到 ans(存储最终掌握单词长度之和)中,当循环结束后返回ans的值。

注:hash表类似python中的字典格式。{'a': 1, 'b':2}

代码:

import collections
from typing import List


def Solution(words: List[str], chars: str) -> int:
chars_cnt = collections.Counter(chars) # 创建 chars 的hash表。
ans = 0
for word in words:
word_cnt = collections.Counter(word) # 获取 words 中各个字符串的hash表
for c in word_cnt:
if chars_cnt[c] < word_cnt[c]: # 将两个hash表之间的元素及数量进行比较
break
else:
ans += len(word) # 将掌握单词长度记录到 ans 中
return ans


print(Solution(["cat","bt","hat","tree"], 'atach')) # 6

 

posted @ 2020-03-17 22:48  河图一号  阅读(136)  评论(0)    收藏  举报