我正在尝试解决两个字符串之间最大公共子串的问题。我将把我的问题简化为以下内容:我创建了一个通用后缀树 http://en.wikipedia.org/wiki/Generalized_suffix_tree根据我的理解,最大的公共子串是由属于两个字符串的节点组成的最深路径。
我的测试输入是:
String1 = xabc
String2 = abc
看来我构建的树是正确的,但我的问题是以下方法(我最初传递树的根):
private void getCommonSubstring(SuffixNode node) {
if(node == null)
return;
if(node.from == ComesFrom.Both){
current.add(node);
}
else{
if(max == null || current.size() > max.size()){
max = current;
}
current = new ArrayList<SuffixNode>();
}
for(SuffixNode n:node.children){
getCommonSubstring(n);
}
}
我的目标是,为了找到包含属于两个字符串的节点的最深路径,我将遍历树(预序)并在列表中添加属于两个字符串的节点(current
)。一旦我处于不属于两者的节点,我就会更新max
列出如果current
更大。
但代码是错误的。我对如何实现这一点感到困惑,因为我已经很久没有为通用(非二元)树编写代码了。
你能帮我解决这个问题吗?
Update:
根据@templatetypedef 进行修改。也无法使这项工作成功。
private void getCommonSubstring(SuffixNode node, List<SuffixNode> nodes) {
if(node == null)
return;
if(node.from == ComesFrom.Both){
nodes.add(node);
}
else{
if(max == null || current.size() > max.size()){
max = nodes;
}
nodes = new ArrayList<SuffixNode>();
}
for(SuffixNode n:node.children){
List<SuffixNode> tmp = new ArrayList<SuffixNode>(nodes);
getCommonSubstring(n, tmp);
}
}
public class SuffixNode {
Character character;
Collection<SuffixNode> children;
ComesFrom from;
Character endMarker;
}