📅  最后修改于: 2023-12-03 15:22:26.217000             🧑  作者: Mango
本程序将给定数组中的字符与给定字典中的单词进行匹配,返回所有可能的有效单词。
本程序输入两个参数:
本程序返回一个字符串列表,包含所有匹配成功的有效单词。
arr = ["o", "r", "l", "p", "w"]
dict = ["world", "hello", "python", "programming"]
print(match(arr, dict))
输出:
["world", "or", "low", "owl"]
本程序的核心思想是使用哈希表存储字典中每个单词中字符的出现次数,然后将给定数组中每个字符的出现次数与哈希表中对应的次数进行比较。
def match(arr, dict):
result = []
hash_dict = {}
for word in dict:
hash_word = {}
for char in word:
hash_word[char] = hash_word.get(char, 0) + 1
hash_dict[word] = hash_word
arr_count = {}
for char in arr:
arr_count[char] = arr_count.get(char, 0) + 1
for word in dict:
match_count = 0
for char in hash_dict[word]:
if char not in arr_count or hash_dict[word][char] > arr_count[char]:
break
else:
match_count += 1
if match_count == len(hash_dict[word]):
result.append(word)
return result
以上即为本程序的主要实现代码。