0

Horspool のアルゴリズム用の Java プログラムを書いていますが、少し問題があります。文字列内の各文字を保持する文字の配列を作成しようとしていますが、文字の重複は望ましくありません。今、これは私のコードです:

public static void main(String[] args) 
{
    Scanner scanIn = new Scanner (System.in);

    int count = 0;

    int count2 = 0;

    int inc = 0;

    //The text to search for the phrase in
    String t = "";

    //The phrase/pattern to search for
    String p = "";

    System.out.println(" ");
    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    System.out.println("Harspool's Algorithm: ");
    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
    System.out.println(" ");
    System.out.println("Please enter the full text: ");
    t = scanIn.nextLine();
    System.out.println("Please enter the pattern to search for: ");
    p = scanIn.nextLine();

    char[] text = new char[t.length()];
    char[] pattern = new char[p.length()];
    char[] alphabet = new char[t.length()];

    for (int i = 0; i < alphabet.length; i++)
    {
        alphabet[i] = ' ';
    }


    for (int i = 0; i < text.length; i++)
    {
        text[i] = t.charAt(i);
    }

    for (int i = 0; i < pattern.length; i++)
    {
        pattern[i] = p.charAt(i);
    }

    while (inc < text.length)
    {
        for (int j = 0; j < text.length; j++)
        {
            if (text[inc] != alphabet[j])
            {
                count++;
            }
            if (count == p.length() - 1 && count2 < text.length)
            {
                alphabet[count2] = text[inc];
                count2++;
                count = 0;
                inc++;
            }
        }
    }

    for (int i = 0; i < alphabet.length; i++)
    {
        System.out.print(alphabet[i]);
    }
}

問題は while ループにあると思いますが、何が問題なのか正確にはわかりません。現時点では、渡された文字列全体を出力しますが、各文字を 1 回だけ出力する必要があります。誰か助けてくれませんか?

4

2 に答える 2

3

各文字の出現回数を数える代わりに、 を使用しSet<Character>ます。セットには一意の要素が含まれているため、そのように重複することはありません。

またはを実行して、 aSetを配列に変換することもできますmySet.toArray(new String[mySet.size()]);mySet.toArray(new String[0]);

于 2013-03-13T20:46:36.620 に答える
0

あなたのコードは読みやすいものではありません。代わりに、次のアルゴリズムの使用を検討してください。

int ccount[256];
int ii;
for(ii=0;ii<256;ii++) ccount[ii]=0;
for (ii = 0; ii < text.length; ii++)
{
    ccount[t.charAt(i)%256]++;
}
for (ii = 0; ii<256; ii++) {
    if(ccount[ii]>0) System.out.printf("%c", ii);
}

編集-初期化されていることを確認し、演算子ccountを使用して0〜255の範囲外の文字をキャプチャしました。%

于 2013-03-13T20:49:52.227 に答える