0

を含むコードがあります

    Collection<String> tok=Arrays.asList(tokens);
    HashSet<String> lookup=new HashSet<String>();  

       while(!lookup.containsAll(tok)&&max<N)
         {
         }

toString() を使用すると、HashSet にコレクションが含まれていても、containsAll メソッドが false を返すことがわかりました。コードで remove メソッドを使用していますが、決して呼び出されません。

目的は、入力文字列と別の k 個の文字列を取り、すべての k 個の文字列を含む入力文字列で最小のサブ シーケンスを検索することです。

1) 入力文字列のインデックス 0 から開始し、最初の k 個の文字列を HashSet に追加します。これは、k 個の異なるトークンを含めることができる最小シーケンスであるためです。

2)その後、範囲 min=0 から max=k を取り、文字列を位置 max に追加し続け、セットにすべてのトークンが含まれるまで max をインクリメントします。

3) すべてのトークンが見つかったら、文字列の位置 min (最初は 0) を削除し、min をインクリメントします。削除後、すべてのトークンが HashSet に存在しない場合。次の反復でステップ 2 がこの min の値から始まる間隔で繰り返されるように、found を false に設定します。

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 が呼び出されたことがないことを示しています。

remove が呼び出されないのに false を返し続けるのはなぜですか?

上記の 2 つの問題が解決されたとしても、おそらく HashSet は機能しないでしょう。

 This is a this test.
 2
 this
 test

インデックス 3 の this はセットに追加されないため、生成された最小間隔は [3-4] ではなく [0-4] になります。したがって、重複する値を含む可能性があり、containsAll メソッドまたは Will を持つコレクションがありますか?文字列のインデックスをキーとして HashMap を使用する必要がありますか?

4

1 に答える 1

1

pasteBin のコードを見ると、 を含むループにあるように見えSystem.out.println(" Increasing Max "+lookup.toString()+" found ="+found);ます。lookup.containsAll(tok)falsefound

その他のポイント:

  • System.exitコードを呼び出さないでください。(まあ、回復できない本当に深刻な例外やエラーをキャッチしない限り、現在解決しようとしている問題では発生しません)。
  • for反復回数が事前にわかっている場合は、ループを使用します。そうしないと、特にループの終了が複数の変数に依存する場合、whileループははるかに読みやすくなります。
  • 問題のより短い解決策 (1 つの画面に収まる場合もあります) については、sublistmethodをご覧ください。
于 2012-11-12T08:19:53.880 に答える