211. Add and Search Word - Data structure design

一、题目

  1、审题

  

  2、分析

    与208不同的是, search() 方法可以传入的单词可以包含 '.' ,代表任意一个字符。

 

二、解答

  1、思路:

    采用 DFS 方式,当查找单词中字符为 '.' 时,从当前 Trie 节点的所有非空子节点开始查找一次,若有一个返回成功,则为 true;若都失败,则 false;

 1 class WordDictionary {
 2 
 3     private TrieNode root;
 4     /** Initialize your data structure here. */
 5     public WordDictionary() {
 6         root = new TrieNode();
 7     }
 8     
 9     /** Adds a word into the data structure. */
10     public void addWord(String word) {
11         TrieNode node = root;
12         for (int i = 0; i < word.length(); i++) {
13             char c = word.charAt(i);
14             if(node.children[c - 'a'] == null)
15                 node.children[c - 'a'] = new TrieNode();
16             node = node.children[c - 'a'];
17         }
18         node.isWord = true;
19     }
20     
21     /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
22     public boolean search(String word) {
23         return search(word, root);
24     }
25 
26     private boolean search(String word, TrieNode node) {
27         for (int i = 0; i < word.length(); i++) {
28             char c = word.charAt(i);
29             // 处理 '.'
30             if(c == '.') {
31                 for(TrieNode child: node.children) {
32                     if(child == null)
33                         continue;
34                     if(search(word.substring(i+1), child))
35                         return true;
36                 }
37                 return false;
38             }
39             if(node.children[c - 'a'] == null)
40                 return false;
41             node = node.children[c - 'a'];
42         }
43         return node.isWord;
44     }
45 }

 

posted @ 2018-10-31 21:01  skillking2  阅读(125)  评论(0编辑  收藏  举报