<分区>
我有一段代码包含
Collection<String> tok=Arrays.asList(tokens);
HashSet<String> lookup=new HashSet<String>();
while(!lookup.containsAll(tok)&&max<N)
{
}
使用 toString() 我发现即使 HashSet 包含一个集合,containsAll 方法仍然返回 false。我在代码中使用了 remove 方法,但它从未被调用。完整代码是 here on pastebin这将更具可读性。
目的是取一个输入字符串和另外k个字符串,并在输入字符串中搜索包含所有k个字符串的最小子序列
1)从输入字符串中的索引0开始,将前k个字符串添加到HashSet中,因为这是可以包含k个不同标记的最小序列
2)之后取范围 min=0 到 max=k 并继续在位置 max 处添加字符串并递增 max 直到集合包含所有标记
3) 当找到所有标记后,删除字符串最小位置(最初为 0)并递增最小值。如果删除后所有标记都不存在于 HashSet 中。将 found 设置为 false,以便在下一次迭代中重复第 2 步,间隔从这个 min 值开始
4)如果max-min小于之前的差,则新的最小子序列为min-max
输入为
This is a test. This is a programming test. This is a programming test in any language.
k=4
this
a
test
programming
输出是
tokens are [this, a, test, programming]
Increasing Max [is, test, a, this] found =false
Increasing Max [is, test, a, this] found =false
Increasing Max [is, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, this] found =false
Increasing Max [is, programming, test, a, in, this] found =false
Increasing Max [is, programming, test, any, a, in, this] found =false
Increasing Max [is, programming, test, any, a, language, in, this] found =false
No subsegment found
输出显示 remove 从未被调用 containsAll() 一直返回 false,即使它包含集合中存在的所有字符串也是如此。
为什么从不调用 remove 却一直返回 false?
即使解决了上述两个问题,HashSet 也可能无法工作。对于像这样的输入
This is a this test.
2
this
test
因为索引 3 处的 this 不会被添加到集合中。生成的最小间隔将是 [0-4] 而不是 [3-4] 那么是否存在一个可能包含重复值并具有 containsAll 方法的集合,或者我必须使用以字符串索引作为键的 HashMap 吗?