Soweit ich es verstanden habe, speichern wir in einem Trie die Zeichen eines Wortes auf ähnliche Weise zu einem Baum, und wir gehen von der Wurzel zum Ende eines Wortes.
Um einen Knoten einzufügen, wird diese Funktion verwendet:
Code: Select all
public void put(char c, Node node) {
links[c - 'a'] = node;
}
Code: Select all
public Node next(char c) {
return links[c - 'a'];
}
Das heißt, in der Funktion put() verwenden wir die Parameter „char c“ und „Node node“ und fügen einen Knoten in das Array der Knoten (Links) ein ), die wir am Anfang gemacht haben. Wenn wir nun die Funktion next() aufrufen, geben wir dann nicht nur den Knoten des Zeichens zurück, das wir eingefügt haben?
Die vollständige Implementierung ist unten angegeben:
(Alle Der angegebene Code ist in Java)
Code: Select all
class Node {
private Node[] links = new Node[26];
// Check if the character is present in the current node
public boolean contains(char c) {
return links[c - 'a'] != null;
}
// Insert a new node for the character
public void put(char c, Node node) {
links[c - 'a'] = node;
}
// Get the next node for the character
public Node next(char c) {
return links[c - 'a'];
}
}
class Trie {
private Node root;
public Trie() {
root = new Node();
}
// Insert a word into the Trie
public void insert(String word) {
Node node = root;
for (char c : word.toCharArray()) {
if (!node.contains(c)) {
node.put(c, new Node());
}
node = node.next(c);
}
}
// Check if the Trie contains a given prefix
public boolean startsWith(String prefix) {
Node node = root;
for (char c : prefix.toCharArray()) {
if (!node.contains(c)) {
return false;
}
node = node.next(c);
}
return true;
}
}