zoukankan      html  css  js  c++  java
  • LeetCode211. 添加与搜索单词

     

     

     分析:把Trie当做字符串的集合来使用,添加单词,查询单词是否存在

     1 import java.util.TreeMap;
     2 class WordDictionary {
     3     private class Node{
     4         public boolean isWord;
     5         public TreeMap<Character, Node> next;
     6 
     7         public Node(boolean isWord){
     8             this.isWord = isWord;
     9             next = new TreeMap<>();
    10         }
    11 
    12         public Node(){
    13             this(false);
    14         }
    15     }
    16     private Node root;
    17 
    18     /** Initialize your data structure here. */
    19     public WordDictionary() {
    20         root = new Node();
    21 
    22     }
    23     
    24     /** Adds a word into the data structure. */
    25     public void addWord(String word) {
    26         Node cur = root;
    27         for(int i = 0; i < word.length(); i++){
    28             char c = word.charAt(i);
    29             if(cur.next.get(c) == null){ // 当前节点的next中是否存在字符c对应的下一个节点的映射
    30                 cur.next.put(c, new Node());
    31             }
    32             cur = cur.next.get(c);
    33         }
    34         cur.isWord = true;
    35 
    36     }
    37     
    38     /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
    39     public boolean search(String word) {
    40         return match(root, word, 0);
    41 
    42     }
    43     private boolean match(Node node, String word, int index){
    44         if(index == word.length()){
    45             return node.isWord;
    46         }
    47         char c = word.charAt(index);
    48         if(c != '.'){
    49             if(node.next.get(c) == null){
    50                 return false;
    51             }
    52             return match(node.next.get(c), word, index + 1);
    53         }
    54         // 等于'.'的情况是node的下一个字符的所有可能都去匹配
    55         else{
    56             for(char nextChar : node.next.keySet()){
    57                 if(match(node.next.get(nextChar), word, index + 1)){
    58                     return true;
    59                 }
    60             }
    61             return false;
    62 
    63         }
    64     }
    65 }
    66 
    67 /**
    68  * Your WordDictionary object will be instantiated and called as such:
    69  * WordDictionary obj = new WordDictionary();
    70  * obj.addWord(word);
    71  * boolean param_2 = obj.search(word);
    72  */
    Solution bobo
  • 相关阅读:
    Silverlight工具荟萃
    微软WindowsPhone7份额已经超过了Symbian
    WPF性能优化经验总结和整理综合帖
    长期提供WindowsPhone7培训 & HTML5培训 & Silverlight培训 & WPF培训
    微软首推msnNOW服务 网络社交化风暴愈演愈烈
    cppunit在vs2008下使用的环境搭建(下)
    [转]ruby中gets 和 gets.chomp 区别
    大四中软实习笔记20130226
    [转]Ruby中require、load和include区别
    大四中软实习笔记20130227
  • 原文地址:https://www.cnblogs.com/HuangYJ/p/12862247.html
Copyright © 2011-2022 走看看