【发布时间】: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