我想打印或检索存储在 Trie 数据结构中的所有单词。这是因为我想计算拼写错误的单词和字典中的单词之间的编辑距离。因此,我正在考虑从 Trie 中检索每个单词并计算编辑距离。但我无法检索。我想要一些代码片段。这就是我HashMap
在 Java中使用 Trie 实现的方式
现在请告诉我如何编写代码来打印存储在 Trie 中的所有单词。很感谢任何形式的帮助
TrieNode.java
package triehash;
import java.io.Serializable;
import java.util.HashMap;
public class TrieNode implements Serializable {
HashMap<Character, HashMap> root;
public TrieNode() {
root = new HashMap<Character, HashMap>();
}
}
TrieDict.java
package triehash;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;;
import java.io.Serializable;
import java.util.HashMap;
import java.io.Serializable;
public class TrieDict {
public TrieNode createTree()
{
TrieNode t = new TrieNode();
return t;
}
public void add(String s, TrieNode root_node) {
HashMap<Character, HashMap> curr_node = root_node.root;
s = s.toLowerCase();
for (int i = 0, n = s.length(); i < n; i++) {
Character c = s.charAt(i);
if (curr_node.containsKey(c))
curr_node = curr_node.get(c);
else {
curr_node.put(c, new HashMap<Character, HashMap>());
curr_node = curr_node.get(c);
}
}
curr_node.put('\0', new HashMap<Character, HashMap>(0)); // term
}
public void serializeDict(TrieNode root_node)
{
try{
FileOutputStream fout = new FileOutputStream("/home/priya/NetBeansProjects/TrieHash/dict.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(root_node);
oos.close();
System.out.println("Done");
}catch(Exception ex){
ex.printStackTrace();
}
}
public void addAll(String[] sa,TrieNode root_node) {
for (String s: sa)
add(s,root_node);
}
public static void main(String[] args)
{
TrieDict td = new TrieDict();
TrieNode tree = td.createTree();
String[] words = {"an", "ant", "all", "allot", "alloy", "aloe", "are", "ate", "be"};
for (int i = 0; i < words.length; i++)
td.add( words[i],tree);
td.serializeDict(tree); /* seriliaze dict*/
}
}