gpt4 book ai didi

java - Java中的Trie实现

转载 作者:行者123 更新时间:2023-12-02 02:56:24 25 4
gpt4 key购买 nike

这是我对 Trie 的实现。

public class Trie {

private class Node{
private Map<Character, Node> children;
boolean end;

public Node(){
children = new HashMap<>();
end = false;
}
}

private Node root;

public Trie(){
root = new Node();
}

public void insert(String word){
Node current = root;
for (int i=0; i < word.length(); i++){
char c = word.charAt(i);
Node node = current.children.get(c);
if(node == null){
node = new Node();
current.children.put(c, node);
}
current = node;
}
}

public boolean search(String word){
Node current = root;
for(int i =0; i < word.length(); i++){
char c = word.charAt(i);
Node node = current.children.get(c);
if(node == null)
return false;
current = node;
}
return current.end;
}
}

我想添加一个方法,给定一个字符串返回其所有子项,可以用作现实世界的自动更正建议。

这是方法签名:

public List<String> returnAllChildren(String str){

}

我对这个有点迷失了。任何帮助表示赞赏。

最佳答案

首先,插入节点时,应在尾节点设置end=true。然后在Trie中查找前缀时,只需找到前缀中最后一个字符的节点,然后递归地获取所有字符串。这是一个示例,也许可以帮助您:

public class Trie {

private class Node{
private Map<Character, Node> children;
boolean end;

public Node(){
children = new HashMap<>();
end = false;
}
}

private Node root;

public Trie(){
root = new Node();
}

public void insert(String word){
Node current = root;
for (int i=0; i < word.length(); i++){
char c = word.charAt(i);
Node node = current.children.get(c);
if(node == null){
node = new Node();
current.children.put(c, node);
}
current = node;
}
// Set end to true
current.end = true;
}

public boolean search(String word){
Node current = root;
for(int i =0; i < word.length(); i++){
char c = word.charAt(i);
Node node = current.children.get(c);
if(node == null)
return false;
current = node;
}
return current.end;
}


private List<String> getAll(String prefix, Node node) {
List<String> r = new ArrayList<>();
if (node.end) {
r.add(prefix);
}
for (Map.Entry<Character, Node> child : node.children.entrySet()) {
List<String> subSuffix = getAll(prefix + child.getKey(), child.getValue());
r.addAll(subSuffix);
}
return r;
}

public List<String> returnAllChildren(String str){
List<String> r = new ArrayList<>();
Node current = root;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
Node node = current.children.get(c);
if (node == null) {
// Not found
return r;
}
current = node;
}
// If you don't need the prefix, you can just
// return getAll("", current);
return getAll(str, current);
}

public static void main(String[] args) {
Trie trie = new Trie();
trie.insert("abc");
trie.insert("abcd");
trie.insert("ab");

List<String> r = trie.returnAllChildren("a");
for (String s : r) {
System.out.println(s);
}
}
}

关于java - Java中的Trie实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43011837/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com