程序媛詹妮弗
终身学习

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or .. A . means it can represent any one letter.

Example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

Note:
You may assume that all words are consist of lowercase letters a-z.

 

题意:

设计一个数据结构,能够插入单词,能够查找字符串,并支持正则表达式中的“.”单字符通配。

 

思路:

这是一道很典型的字典树(Trie)的题目,唯一的变化是在字典树查找的过程中引入了通配符.,通配符匹配可以通过回溯法(枚举26个英文)实现。

字典树(Trie)是面试中常见的题型,也叫做前缀树,是一种用来快速检索的多叉树结构。对于本题而言,需要构造的是一个英文字母字典树,因此是一个26叉树。

字典树可以利用字符串的公共前缀来节约存储的空间并加快检索的速度。下图中的字典树包含了五个英文单词dad, do, dog, done, bi:

 

字典树有如下基本性质:

  1. 字典树的根节点不包含字符,代表一个空字符串;
  2. 从根节点到某节点,路径上经过的字符连接起来即为该节点所代表的字符串;
  3. 每个节点所代表的字符串各不相同,父节点代表的字符串一定是它孩子节点代表的字符串的前缀

 

代码:

 1 class WordDictionary {
 2     
 3     private TrieNode root;
 4     
 5     /** Initialize your data structure here. */
 6     public WordDictionary() {
 7         root = new TrieNode();
 8     }
 9     
10     /** Adds a word into the data structure. */
11     public void addWord(String word) { // bad
12         TrieNode node = root; // 初始化node
13         for(int i = 0; i< word.length();i++){ // 遍历bad的每个char
14             int j = word.charAt(i)-'a'; //  j = 62-61 = 1
15             if(node.children[j]==null){ // 
16                 node.children[j]=new TrieNode();
17             }
18             node = node.children[j];
19         }
20         node.isWord = true;
21         node.word = word;   
22     }
23     
24     /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
25     public boolean search(String word) {
26         return find(word,root,0);
27     }
28     
29     // recursively checking each char 
30     public boolean find(String word, TrieNode node, int index){
31         if(index == word.length()) return node.isWord;
32         if(word.charAt(index) =='.') {
33             for(TrieNode temp : node.children){
34                 if(temp!=null && find(word,temp,index+1)) return true;
35             }
36             return false;
37         } else{
38             int j = word.charAt(index) - 'a';
39             TrieNode temp = node.children[j];
40             return temp !=null && find(word, temp, index+1);
41         }
42     }
43 }
44 
45 
46 class TrieNode{
47     TrieNode[] children;
48     boolean isWord;
49     String word;
50     
51     public TrieNode(){
52         children = new TrieNode[26];
53         isWord = false;
54         word = "";
55     }
56 }

 

posted on 2018-10-18 14:16  程序媛詹妮弗  阅读(122)  评论(0编辑  收藏  举报