【发布时间】:2012-11-12 05:29:50
【问题描述】:
我有一段代码包含
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)当找到所有标记时,删除字符串一个位置 min(最初为 0)并增加 min。如果删除后所有标记都不存在于 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?
【问题讨论】:
-
清理代码的缩进和换行。现在很难阅读。
-
我现在尝试正确缩进,但由于我无法立即查看代码的完整视图,我无法查看所有行是否正确缩进。现在重新检查
-
问题太多。请在每个帖子中提出一个问题,请参阅 How to Ask 和 FAQ。
-
是的,有 4 个问题,但 1,2 和 4 非常相关,它们都是关于基于哈希结构的 contains 方法的一致性。我应该将它们移动到不同的帖子吗?
-
@JimGarrison 我在这里发布了与此代码无关的问题stackoverflow.com/questions/13339973/… 将从这篇文章中删除它们