【问题标题】:Comparing two lists of Strings and counting the matches, possible performance problem比较两个字符串列表并计算匹配项,可能存在性能问题
【发布时间】:2021-05-05 17:48:49
【问题描述】:

在比较字符串列表 A 和另一个字符串列表 B 时,我想计算匹配的数量。A 包含来自集合 Z 的元素,而 B 是 Z 的子集。A 可以包含重复项,但 B 不能。我希望单独计算重复项,因此与 B 中的相同元素的 2x 匹配应该产生 2 个计数。 列表 A 的字符串包含我决定删除的前缀,但我也可以不修改原始字符串元素

例子:

List<string> A = {"a","b","c","a"}
List<string> B = {"a", "c"}

匹配数为 3(与 a 匹配两次,与 c 匹配一次)

我有一个应该有效的解决方案,并且在极少数情况下它确实有效,但我怀疑由于执行期间的时间限制,它在 90% 的情况下都失败了。

var _A = A.Select(str => str.ToLower()).ToList(); //B can be modified for this step to be not necessary but increases the length of each string element
_A = _A.Select(str => str.Replace(" ", "")).ToList(); //B can be modified for this step to be not necessary but increases the length of each string element
_A = _A.Select(x => x.Substring("drops".Length)).ToList(); //B can be modified for this step to be not necessary but increases the length of each string element

sum = _A.Where(x => B.Any(y => y.Equals(x))).Count();

如果我没记错的话,这是O(A*B)

我还能做些什么来降低时间复杂度?

【问题讨论】:

    标签: c# string list linq matching


    【解决方案1】:

    您使用HashSet&lt;string&gt;Add()Contains() 都是 O(1)。

    var a = new[] { "a", "b", "c", "a" };
    var b = new[] { "a", "c" };
    
    var hs = new HashSet<string>(b);
    var cnt = a.Count(x => hs.Contains(x));
    

    这复杂度为 O(b+a),Add() 的复杂度为 O(b),Contains() 的复杂度为 O(A)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-20
      • 2021-02-04
      • 2019-12-26
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多