问题描述
在比较字符串列表 A 和另一个字符串列表 B 时,我想计算匹配的数量。A 包含来自 Set 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)
。
我还能做些什么来降低时间复杂度吗?
解决方法
您使用了 HashSet<string>
。在 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)。