【发布时间】:2015-10-06 21:56:33
【问题描述】:
我正在研究一些后缀树实现,这是一个参考实现,问题是“索引”(参见第 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());
}
}
}
}
【问题讨论】:
-
我运行了您的代码,它按设计运行。如果你有一个错误,假设你没有减少字符串,你会得到一个 stackoverflow 异常,因为你永远不会遇到你的递归基本情况并陷入永远循环
标签: java algorithm trie suffix-tree