在Java中调试Trie结构

时间:2016-09-21 03:21:48

标签: java debugging trie

以下是我用Java制作的Trie结构,支持insertsearch

我添加了一个新字段outDegree,这是一个数字,只要字符添加到结构中,该字段就会递增。

public class Trie {
    private class Node {
        Node[] children;
        int outDegree;
        boolean isLeaf;

        Node() {
            this.children = new Node[26]; // Assuming the word is only going to contain 26 alphabets
            this.isLeaf = false;
            this.outDegree = 0;
        }
    }

    private Node root;

    public Trie() {
        root = new Node();
    }

    public Node insert(String word) {
        if (word == null)
            return null;

        Node currentNode = root;
        for (int i = 0; i < word.length(); i++) {
            int index = word.charAt(i) - 'a';
            if (currentNode.children[index] == null) {
                currentNode.children[index] = new Node();
            }
            currentNode.outDegree++;
            System.out.println(currentNode.outDegree + "\t" + word.charAt(i) + "\t" + index);
            currentNode = currentNode.children[index];
        }
        currentNode.isLeaf = true;
        return currentNode;
    }

    private Node searchNode(String word) {
        if (word == null)
            return null;

        Node currentNode = root;
        for (int i = 0; i < word.length(); i++) {
            int index = word.charAt(i) - 'a';
            if (currentNode.children[index] == null)
                return null;
            System.out.println(currentNode.outDegree + "\t" + word.charAt(i));
            currentNode = currentNode.children[index];
        }
        return currentNode;
    }

    public boolean search(String word) {
        Node lastNode = searchNode(word);
        return lastNode != null && lastNode.isLeaf;
    }

    public boolean startsWith(String prefix) {
        return prefix != null && searchNode(prefix) != null;
    }

    public static void main(String[] args) {
        Trie trie = new Trie();
        trie.insert("animesh");
        System.out.println();
        trie.insert("animation");
        System.out.println(trie.search("animesh"));   // true
        System.out.println(trie.search("animation")); // true
        System.out.println(trie.startsWith("anime")); // true
        System.out.println(trie.startsWith("animo")); // false
    }
}

输出格式:outDegree字符索引

实际输出:

1   a   0
1   n   13
1   i   8
1   m   12
1   e   4
1   s   18
1   h   7

2   a   0
2   n   13
2   i   8
2   m   12 ==> the two strings match till "anim". Here should be the last increment
2   a   0  ==> wrong outDegree. Node[] has all outDegree's as 0, so why it was 1 here?
1   t   19
1   i   8
1   o   14
1   n   13

预期输出:

1   a   0
1   n   13
1   i   8
1   m   12
1   e   4
1   s   18
1   h   7

2   a   0
2   n   13
2   i   8
2   m   12 ==> the two strings match till "anim"
1   a   0  ==> the outDegree should be 1 and not 2
1   t   19
1   i   8
1   o   14
1   n   13

我无法在代码中找到引起此问题的部分?

0 个答案:

没有答案