java - 检查 HashSet 是否包含特定子集

标签 java algorithm hashset

<分区>

我有一段代码包含

    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 吗?

最佳答案

查看 pasteBin 上的代码,似乎在包含 System.out.println("Increasing Max "+lookup.toString()+"found ="+found); 的循环中, 您永远不会调用 lookup.containsAll(tok),即它在每次循环迭代中输出 false 的事实是由于 found 之前为 false。

其他几点:

  • 不要在您的代码中调用System.exit。 (好吧,除非你发现了一个非常严重的异常或错误,你无法从中恢复,这不会发生在你当前试图解决的问题上)。
  • 如果您事先知道迭代次数,请使用for 循环。如果不这样做,尤其是如果循环终止取决于多个变量,while 循环将更具可读性。
  • 要更简短地解决您的问题(甚至可能适合一个屏幕),请查看 sublist method .

关于java - 检查 HashSet 是否包含特定子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13338812/

相关文章:

java - 将 JSON 发送到 Spark Streaming 时如何保留 JSON 结构

java - Spring REST 模板接受 header

java - OpenNLP 解析器训练

java - HashSet - 确保早期对象持久化

java - 注入(inject) JpaRepository : Error creating bean with name

algorithm - 用于查找缺少字母的单词的良好算法和数据结构?

c# - 比较两个频谱图以找到它们匹配算法的偏移量

java - 从句子中提取短语的算法

java - 最快的 Java HashSet<Integer> 库

c# - 使用哈希表的不同值