Java 从Trie数据结构中获取单词
我有以下Trie数据结构:Java 从Trie数据结构中获取单词,java,search,trie,Java,Search,Trie,我有以下Trie数据结构: public class CDictionary implements IDictionary { private static final int N = 'z' -'a'+1; private static class Node { private boolean end = false; private Node[] next = new Node[N]; } private int size = 0; private Node root
public class CDictionary implements IDictionary {
private static final int N = 'z' -'a'+1;
private static class Node {
private boolean end = false;
private Node[] next = new Node[N];
}
private int size = 0;
private Node root = new Node();
@Override
public boolean contains(String word) {
Node node = this.contains(root,word,0);
if (node == null) {
return false;
}
return node.end;
}
private Node contains(Node node, String str, int d) {
if (node == null) return null;
if (d == str.length()) return node;
char c = str.charAt(d);
return contains(node.next[c-'a'], str, d+1);
}
@Override
public void insert(String word) {
this.root = insert(this.root, word, 0);
this.size++;
}
private Node insert(Node node, String str, int d) {
if (node == null) node = new Node();
if (d == str.length()) {
node.end = true;
return node;
}
char c = str.charAt(d);
node.next[c-'a'] = this.insert(node.next[c-'a'], str, d+1);
return node;
}
@Override
public int size() {
return size;
}
Trie中充满了一些单词,如
因为,这个,每个,家,是,它,鸡蛋,红色
现在我需要一个函数来获取具有特定长度的所有单词,例如长度3
public List<String> getWords(int lenght) {
}
public List getWords(整数长度){
}
对于上面提到的单词,它应该返回一个包含单词的列表
因为,鸡蛋,红色
问题是如何从Trie结构中恢复这些单词?您需要在结构中递归到最大深度N(在本例中为3) 您可以通过在字典中添加几个方法来实现这一点
public List<String> findWordsOfLength(int length) {
// Create new empty list for results
List<String> results = new ArrayList<>();
// Start at the root node (level 0)...
findWordsOfLength(root, "", 0, length, results);
// Return the results
return results;
}
public void findWordsOfLength(Node node, String wordSoFar, int depth, int maxDepth, List<String> results) {
// Go through each "child" of this node
for(int k = 0; k < node.next.length; k++) {
Node child = node.next[k];
// If this child exists...
if(child != null) {
// Work out the letter that this child represents
char letter = 'a' + k;
// If we have reached "maxDepth" letters...
if(depth == maxDepth) {
// Add this letter to the end of the word so far and then add the word to the results list
results.add(wordSoFar + letter);
} else {
// Otherwise recurse to the next level
findWordsOfLength(child, wordSoDar + letter, depth + 1, maxDepth, results);
}
}
}
}
公共列表findWordsOfLength(int-length){
//为结果创建新的空列表
列表结果=新建ArrayList();
//从根节点(级别0)开始。。。
findWordsOfLength(根,“”,0,长度,结果);
//返回结果
返回结果;
}
public void findWordsOfLength(节点节点、字符串字、int-depth、int-maxDepth、列表结果){
//检查此节点的每个“子节点”
for(int k=0;k
(我还没有编译/测试过这个,但它应该能让你知道你需要做什么)
希望这能有所帮助。事实上,当传入“3”时,这可能会找到长度为“4”的单词,就像我说的,而不是测试它。。。您可能还必须检查最后一个节点是否为terminal(即,除非其所有子节点都为空,否则不要将其添加到结果列表中…)。谢谢,这确实有效。我已经解决了单词长度的问题。我以深度1开始递归方法