从TRIE数据结构中检索字符串时,数组索引超出范围?

时间:2014-04-16 18:18:05

标签: java data-structures trie

我将字符串及其频率存储在TRIE数据结构中

hello 100
world 5000
good 2000
bad 9000

以下是我的TrieImpl课程

public class TrieImpl {

    //root node
    private TrieNode r;

    public TrieImpl() {
        r = new TrieNode();
    }

    public int find(String word) {
        return r.getFreq(word);
    }

    public void insert(String word, int freq) {
        r.insert(word, freq);
    }

    public String toString() {
        return r.toString();
    }

    public static void main(String[] args) {

        TrieImpl t = new TrieImpl();

        System.out.println("Testing some strings");
        // storing strings and its frequencies
        t.insert("HELLO", 10);
        t.insert("WORLD", 20);

        System.out.println(t.find("HELLO"));
        System.out.println(t.find("HELLO1")); // this line throws Array Index Out of Range
    }
}

以下是我的TrieNode class -

public class TrieNode {

    // make child nodes
    private TrieNode[] c;
    // flag for end of word
    private boolean flag = false;
    // stores frequency if flag is set
    private int frequency;

    public TrieNode() {
        c = new TrieNode[26];
    }

    protected void insert(String word, int frequency) {
        int val = word.charAt(0) - 64;

        // if the value of the child node at val is null, make a new node
        // there to represent the letter
        if (c[val] == null) {
            c[val] = new TrieNode();
        }

        // if the value of the child node at val is null, make a new nod
        if (word.length() > 1) {
            c[val].insert(word.substring(1), frequency);
        } else {
            c[val].flag = true;
            c[val].frequency = frequency;
        }
    }


    public int getFreq(String word) {
        int val = word.charAt(0) - 64;
        if (word.length() > 1) {
            return c[val].getFreq(word.substring(1));
        } else if (c[val].flag == true && word.length() == 1) {
            return c[val].frequency;
        } else
            return -1;
    }


    public String toString() {
    return c.toString();
    }
}

我能够在TRIE中插入字符串及其频率,并且还能够查找已经存在的给定字符串的频率。现在我面临的问题是 - 如果我正在寻找一个在TRIE中不存在的字符串,它会抛出Arrays Index Out of Range错误。

如果你看到我上面的TrieImpl类,我正在搜索TRIE中没有的字符串HELLO1,所以对于这种情况,它会抛出ArrayIndex超出范围。

有任何想法如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您只需检查val功能中getFreq是否超出范围。

你可能还需要检查目标索引上是否有一个元素(即它不是null)。

另外,正如在另一个答案中指出的那样,你将一个'无效'字符串传递给你的函数,因为1会导致一个负val值/索引 - 要么你应该避免做这个,或者您也可以将该检查添加到您的函数中。

public int getFreq(String word) {
  int val = word.charAt(0) - 64;
  if (val < 0 || val >= c.length || c[val] == null)
    return -1;
  ...
}

答案 1 :(得分:1)

您正在使用:t.find("HELLO1"),它将传递给您的getFreq()函数。

它将继续使用getFreq()ELLO1LLO1LO1

致电O1

此时,当实施重试它时,只有1字由于您的递归方式,它将导致int val = word.charAt(0) - 64; // 49-64并且值为val = -15 - 而且&#39 ; s不是有效的数组索引。