后缀树实现问题

时间:2015-10-06 21:56:33

标签: java algorithm trie suffix-tree

我正在研究一些后缀树实现,这里有一个参考实现,问题是"索引" (参考第19行)用于SuffixTreeNode类?我不确定"索引"是有用的,我想我们可能只需要保持所有节点及其子节点的价值?找不到太多的"索引"用于SuffixTreeNode类。

请随时纠正我。任何见解都表示赞赏。

public class SuffixTree {
    SuffixTreeNode root = new SuffixTreeNode();
    public SuffixTree(String s) {
        for (int i = 0; i < s.length(); i++) {
            String suffix = s.substring(i);
            root.insertString(suffix, i);
        }
    }

    public ArrayList<Integer> getIndexes(String s) {
        return root.getIndexes(s);
    }
 }

public class SuffixTreeNode {
    HashMap<Character, SuffixTreeNode> children = new
    HashMap<Character, SuffixTreeNode>();
    char value;
    ArrayList<Integer> indexes = new ArrayList<Integer>();
    public SuffixTreeNode() { }

    public void insertString(String s, int index) {
        indexes.add(index);
        if (s != null && s.length() > 0) {
            value = s.charAt(0);
            SuffixTreeNode child = null;
            if (children.containsKey(value)) {
                child = children.get(value);
            } else {
                child = new SuffixTreeNode();
                children.put(value, child);
            }
            String remainder = s.substring(1);
            child.insertString(remainder, index);
        }
    }

    public ArrayList<Integer> getIndexes(String s) {
        if (s == null || s.length() == 0) {
            return indexes;
        } else {
            char first = s.charAt(0);
            if (children.containsKey(first)) {
                String remainder = s.substring(1);
                return children.get(first).getIndexes(remainder);
            }
        }
        return null;
    }
}

public class Question {
    public static void main(String[] args) {
        String testString = “mississippi”;
        String[] stringList = {“is”, “sip”, “hi”, “sis”};
        SuffixTree tree = new SuffixTree(testString);
        for (String s : stringList) {
            ArrayList<Integer> list = tree.getIndexes(s);
            if (list != null) {
                System.out.println(s + “: “ + list.toString());
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您正在查看后缀树的实现肯定需要

indexes(有多个版本的后缀树比其他版本更优化)。 indexes变量在返回索引时起着不可或缺的作用,其中原始字符串(密西西比)中的子字符串(是,sip,hi,sis)返回到调用方法。 getIndexes在其基本情况下返回indexes,这是您获取每个子字符串的出现列表的方式。见下面的输出

is: [1, 4]
sip: [6]
sis: [3]