黑客等级稀疏数组

问题描述 投票:0回答:2

有一个输入字符串集合和一个查询字符串集合。对于每个查询字符串,确定它在输入字符串列表中出现的次数。返回结果数组。 例子:- strings = ['ab','ab','abc'] queries = ['ab', 'abc', 'bc'] 有 2 个“ab”实例,1 个“abc”实例,0 个“bc”实例。对于每个查询,将一个元素添加到返回数组。 结果 = [2,1,0]

功能说明

在下面的编辑器中完成函数matchingStrings。该函数必须返回一个整数数组,表示每个查询字符串在字符串中出现的频率。

matchingStrings 有以下参数:

string strings[n] - 要搜索的字符串数组 string queries[q] - 查询字符串数组 退货

int[q]:每个查询的结果数组

约束条件:

1 <=len(strings) <= 1000,

1 <=len(queries) <= 1000 1 <= string[i] <= 20,

1<=query[i]<= 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())
                            
python sparse-matrix
2个回答
0
投票

试试这个:

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]

0
投票
def matchingStrings(strings, queries):
    # Write your code here
    output = []
    for i in range(len(queries)):
        output.append(strings.count(queries[i]))

    return output

© www.soinside.com 2019 - 2024. All rights reserved.