0

I'm writing a Java program for Horspool's algorithm, and am having a bit of trouble. I'm trying to create an array of chars that will hold each letter in a string, but I don't want duplicates of the letters. Right now this is my code:

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]);
    }
}

I believe the problem is in the while loop, but I can't figure out what exactly is going wrong. Right now, it will print out the entire string passed in, when it should be printing each letter only once. Could someone please help?

4

2 回答 2

3

不是计算每个字符的出现次数,而是使用Set<Character>。一个集合包含独特的元素,因此您不会有重复。

您还可以通过执行或仅将 a 转换Set为数组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 回答