【问题标题】:How to print all words stored in a Tree , wherin trie has been implemented using Hashmap in Java?如何打印存储在 Tree 中的所有单词,其中已使用 Java 中的 Hashmap 实现 trie?
【发布时间】:2013-04-07 02:53:03
【问题描述】:

我想打印或检索存储在 Trie 数据结构中的所有单词。这是因为我想计算拼写错误的单词和字典中的单词之间的编辑距离。 因此,我正在考虑从 Trie 中检索每个单词并计算编辑距离。 但我无法检索。我想要一些代码sn-p。 这就是我在 Java 中使用 HashMap 实现 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*/
 }   
}

【问题讨论】:

    标签: java hashmap trie


    【解决方案1】:

    首先,值得注意的是root 实例变量的声明类型有点奇怪。 (具体来说,HashMap&lt;Character,HashMap&gt; 的值类型不包括您希望它使用的一些泛型。)下面的代码应该可以工作,但您会因此收到一些警告。您可以尝试重构代码以改用 HashMap&lt;Character,TrieNode&gt; 类型。对不起,如果那是迂腐的。 :)

    试试这个,作为方法添加到TrieNode

    public Set<String> computeWords() {
        Set<String> result;
    
        if(root.size() == 0)
            result = new HashSet<String>();
        else
            result = computeWords(root, "");
    
        return result;
    }
    
    protected static Set<String> computeWords(HashMap tree, String prefix) {
        Set<String> result=new HashSet<String>();
    
        if(tree.size() == 0)
            result.add(prefix);
        else
            for(Object o : tree.keySet()) {
                Character c=(Character) o;
                prefix = prefix+c;
                result.addAll(computeWords((HashMap) tree.get(c), prefix));
                prefix = prefix.substring(0, prefix.length()-1);
            }
    
        return result;
    }
    

    对于给定的TrieNode 对象tt.computeWords() 将返回在t 中编码的所有单词的集合。

    我相信这回答了你想问的问题。但是,要回答标题中所述的问题,您需要打印相同 t 的所有单词,如下所示:

    for(String word : t.computeWords())
        System.out.println(word);
    

    另外,这绝对不是最有效的实现,尤其是我们在computeWords(HashMap,String) 中创建了一堆HashSet 对象,但它应该可以工作!

    编辑:此代码还假设您以空的HashMap 终止单词。如果您改为使用null 终止单词,则需要使用if(tree == null) 更新static 方法中的if(tree.size() == 0) 检查。抱歉,应该说出来的。

    编辑:解释了如何打印所有单词,以防万一不清楚。

    编辑:修复空特里案例。

    【讨论】:

    • @sigpwned.. 感谢您的帮助。我现在面临另一个问题。下面的代码不起作用 String word1="ant" Set Words = ts.computeWords(tree.root); if (Words.contains(word1)) System.out.println("单词存在");
    • 嗨@user2281107。这听起来像是一个单独的问题,因此您可能应该将其作为另一个顶级问题提出。
    猜你喜欢
    • 1970-01-01
    • 2017-09-03
    • 2017-07-18
    • 2022-11-25
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2013-07-25
    • 2016-05-17
    相关资源
    最近更新 更多