码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode211. 添加与搜索单词 - 数据结构设计(相关话题:Trie前缀树)

时间:2020-05-10 13:21:39      阅读:60      评论:0      收藏:0      [点我收藏+]

标签:extc   class   ++   cte   image   one   keyset   this   color   

技术图片

 

 技术图片

 

 技术图片

 

技术图片
 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

 

LeetCode211. 添加与搜索单词 - 数据结构设计(相关话题:Trie前缀树)

标签:extc   class   ++   cte   image   one   keyset   this   color   

原文地址:https://www.cnblogs.com/HuangYJ/p/12862247.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!