有一个输入字符串集合和一个查询字符串集合。对于每个查询字符串,确定它在输入字符串列表中发生的次数。返回结果的数组。例如:字符串= 'ab','ab','abc‘查询= 'ab',’abc','bc‘有2个’ab',1个'abc',0个'bc‘。对于每个查询,向返回数组添加一个元素。结果= 2,1,0
函数描述
在下面的编辑器中完成函数matchingStrings。函数必须返回一个整数数组,表示字符串中每个查询字符串出现的频率。
matchingStrings具有以下参数:
字符串字符串n-用于搜索字符串queriesq的字符串数组-查询字符串的数组返回。
intq:每个查询的结果数组
制约因素:
1<=len(字符串) <= 1000,
1<=len(查询) <= 1000 1 <= 20,
1<=queryi<= 20
这是我的密码。它在示例测试用例上成功运行,但在10/13测试用例中失败。
#Code in python
def matchingStrings(strings, queries):
#first few lines satisfies the constraints
if len(strings) >= 1 and len(strings)<= 1000:
if len(queries)>= 1 and len(strings)<= 1000:
count_arr = {} # creating a dict to save each query count
for query in queries:
if len(query)>= 1 and len(query)<= 20:
count_arr[query] = 0
for string in strings:
if len(string)>= 1 and len(string)<= 20:
if query == string.strip():
count_arr[query] = count_arr[query] + 1
return list(count_arr.values())发布于 2022-11-03 16:04:16
试试这个:
from collections import Counter
def matchingStrings(strings, queries):
count = Counter(strings)
return [count[query] for query in queries]示例:
>>> matchingStrings(['ab', 'ab', 'abc'], ['ab', 'abc', 'bc'])
[2, 1, 0]如果不能使用collections.Counter,则可以实现您的版本:
def matchingStrings(strings, queries):
count = {}
for s in strings:
count[s] = count.get(s, 0) + 1
return [count.get(query, 0) for query in queries]https://stackoverflow.com/questions/74306034
复制相似问题