我正在实现一个后缀树(这与后缀树不同),它将字符串的字符后缀存储为树结构中的节点,其中通过遍历树直到你点击'$'或者你点击您的搜索结束。
问题在于,在使用大型文本文件时,构造这个 trie 会比 Java 消耗更多的内存。有没有什么地方可以减少数据结构方面的内存使用?这是家庭作业,不需要将其制成压缩后缀树(基本上是后缀树)。
这是我目前拥有的基本结构(如果你真的想要,我可以提供实现细节):
// SuffixTrie.java
public class SuffixTrie {
private SuffixTrieNode root = new SuffixTrieNode();
// implementation of insertions into tree etc..
public static void main(String[] args) throws FileNotFoundException {
String fileName = "Frankenstein.txt";
SuffixTrie st = readInFromFile(fileName);
String[] ss = {"without","hideous", "the only", "onster", ", the", "ngeuhhh"};
for (String s: ss) {
SuffixTrieNode sn = st.get(s);
System.out.println("[" + s + "]: " + sn);
}
}
}
每个节点是:
// SuffixTrieNode.java
public class SuffixTrieNode {
private char label; // Indicates the letter for this node
private boolean isTerminal = false;
private SuffixTrieData data;
private HashSet<SuffixTrieNode> children;
// Inserting adds more SuffixTrieNodes to the children of the node
每个节点中保存的数据是:
public class SuffixTrieData {
private ArrayList<Pair> startIndexes = new ArrayList<Pair>();
public SuffixTrieData(int sentence, int index){
addStartIndex(sentence, index);
}
public class Pair{
public int sentence;
public int index;
public Pair(int sentence, int index){
this.sentence = sentence;
this.index = index;
}
}
}
我得到的错误是:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.ArrayList.<init>(Unknown Source)
at java.util.ArrayList.<init>(Unknown Source)
at SuffixTrieData.<init>(SuffixTrieData.java:7)
at SuffixTrie.insert(SuffixTrie.java:20)
at SuffixTrie.insert(SuffixTrie.java:11)
at SuffixTrie.readInFromFile(SuffixTrie.java:77)
at SuffixTrie.main(SuffixTrie.java:89)
虽然它适用于较小的文本文件,但这是他们第一次给学生这个作业,所以教师不知道这是否可以使用后缀 trie..