Java 如何建立Patricia Trie图的模型
我正在尝试为Patricia Trie数据结构实现insert方法。因此,如果我插入字符串Java 如何建立Patricia Trie图的模型,java,graph,Java,Graph,我正在尝试为Patricia Trie数据结构实现insert方法。因此,如果我插入字符串aba,那么字符串abc将在屏幕截图中得到以下trie。 我已经尝试过这段代码,但我不知道如何将图形建模为输出,如何在不使用node1、node2、node3等的情况下根据需要创建多个节点 参与类: package patriciaTrie; import java.util.Scanner; public class Patricia { private Node root; pr
aba
,那么字符串abc
将在屏幕截图中得到以下trie。
我已经尝试过这段代码,但我不知道如何将图形建模为输出,如何在不使用node1、node2、node3等的情况下根据需要创建多个节点
参与类:
package patriciaTrie;
import java.util.Scanner;
public class Patricia {
private Node root;
private Node parent;
private Node node1;
private Node node2;
// create a new node
public Patricia() {
root = null;
parent = null;
}
// inserts a string into the trie
public void insert(String s) {
if (root == null) {
root = new Node(s, "o-");
parent = new Node("-o");
} else {
insert(root, s);
}
}
private void insert(Node root, String s) {
int len1 = root.edge.length();
int len2 = s.length();
int len = Math.min(len1, len2);
for (int index = 0; index < len; index++) {
if (s.charAt(index) != root.edge.charAt(index)) {
// In case the string are not equal, then split them.
String samesubString = s.substring(0, index);
String substringSplit1 = root.edge.substring(index);
String substringSplit2 = s.substring(index);
root.edge = samesubString;
node1 = new Node(substringSplit1, "-o");
node2 = new Node(substringSplit2, "-o");
System.out.println(root.value + root.edge + node1.value +node1.edge + node2.value + node2.edge);
} else {
System.out.println("They are the same - " + index);
}
}
}
public static void main(String[] args) {
Patricia p = new Patricia();
Scanner s = new Scanner(System.in);
while (s.hasNext()) {
String op = s.next();
if (op.equals("INSERT")) {
p.insert(s.next());
}
}
}
}
package patriciaTrie;
public class Node {
String edge;
String value;
Node(String edge, String value) {
this.edge = edge;
this.value = value;
}
Node(String value){
this.value = value;
}
}
使用跟随器边的数组或列表,而不是仅使用一条边。 在图中通常使用跟随边列表,这对于trie来说并没有什么特别的 要构建Patricia trie,请使用与以下类似的节点类:
public class TrieNode {
String value;
// The outgoing (downstream) neighbour nodes
List<TrieNode> next; // probably LinkedList
/** Default Constructor with value */
public TrieNode(String value) {
this.value = value
}
}
在您的示例中,您可以构建图形:
TrieNode nodeRoot = new TrieNode ("ab");
TrieNode nodeLeft = new TrieNode ("a");
TrieNode nodeRight = new TrieNode ("c");
nodeRoot.next.add(nodeLeft);
nodeRoot.next.add(nodeRight);
我不知道是谁投了反对票。好吧,代码是错的,反对票是可以的,但它应该被评论,谁投过票。现在它是正确的。一个节点有许多跟随者;事实上,节点代表边缘,它是一个EdgeNode,修复了另一个bug:现在“next”更具描述性,即传出的edgesI不需要Node类!?
TrieNode nodeRoot = new TrieNode ("ab");
TrieNode nodeLeft = new TrieNode ("a");
TrieNode nodeRight = new TrieNode ("c");
nodeRoot.next.add(nodeLeft);
nodeRoot.next.add(nodeRight);