Question

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.

For 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.

Solution

This kind of problem (searching a String) can be solved by Trie.

We use DFS to implement search. Notice corner cases.

When we choose to implement it by recursion, think one step each time.

 class TrieNode {
public char value;
public boolean isLeaf;
public HashMap<Character, TrieNode> children; public TrieNode(char c) {
value = c;
children = new HashMap<Character, TrieNode>();
isLeaf = false;
}
} public class WordDictionary {
public TrieNode root; public WordDictionary() {
root = new TrieNode('!');
} // Adds a word into the data structure.
public void addWord(String word) {
TrieNode currentNode = root;
for (int i = 0; i < word.length(); i++) {
char tmp = word.charAt(i);
HashMap<Character, TrieNode> children = currentNode.children;
TrieNode nextNode;
if (children.containsKey(tmp)) {
nextNode = children.get(tmp);
} else {
nextNode = new TrieNode(tmp);
children.put(tmp, nextNode);
}
currentNode = nextNode;
// Check whether it's the last character
if (i == word.length() - 1)
currentNode.isLeaf = true;
}
} // Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
public boolean search(String word) {
return dfsSearch(word, 0, root);
} private boolean dfsSearch(String word, int index, TrieNode prevNode) {
// If prevNode is null but word has not been completely traversed, return fasle
if (prevNode == null) {
return false;
} // If word has been completely traversed, check whether tree is at bottom
if (index == word.length()) {
return prevNode.isLeaf;
}
char target = word.charAt(index);
HashMap<Character, TrieNode> currentMap = prevNode.children; if (target != '.') {
if (!currentMap.containsKey(target))
return false;
else
return dfsSearch(word, index + 1, currentMap.get(target));
} else {
boolean result = false;
for (Character key : currentMap.keySet()) {
if (dfsSearch(word, index + 1, currentMap.get(key))) {
result = true;
}
}
return result;
}
}
} // Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");

Add and Search Word - Data structure design 解答的更多相关文章

  1. leetcode面试准备:Add and Search Word - Data structure design

    leetcode面试准备:Add and Search Word - Data structure design 1 题目 Design a data structure that supports ...

  2. 【LeetCode】211. Add and Search Word - Data structure design

    Add and Search Word - Data structure design Design a data structure that supports the following two ...

  3. 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design

    字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...

  4. LeetCode208 Implement Trie (Prefix Tree). LeetCode211 Add and Search Word - Data structure design

    字典树(Trie树相关) 208. Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith  ...

  5. 【刷题-LeetCode】211. Add and Search Word - Data structure design

    Add and Search Word - Data structure design Design a data structure that supports the following two ...

  6. (*medium)LeetCode 211.Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  7. 211. Add and Search Word - Data structure design

    题目: Design a data structure that supports the following two operations: void addWord(word) bool sear ...

  8. [Swift]LeetCode211. 添加与搜索单词 - 数据结构设计 | Add and Search Word - Data structure design

    Design a data structure that supports the following two operations: void addWord(word) bool search(w ...

  9. LeetCode——Add and Search Word - Data structure design

    Description: Design a data structure that supports the following two operations: void addWord(word) ...

随机推荐

  1. poj2739

                                                                                           Sum of Consec ...

  2. [转载]用可变参数宏(variadic macros)传递可变参数表

    注意:_VA_ARGS__ 从VS2005才开始支持 在 GNU C 中,宏可以接受可变数目的参数,就象函数一样,例如: #define pr_debug(fmt,arg...) printk(KER ...

  3. hdu 1429 胜利大逃亡(续)(bfs+状态压缩)

    Problem Description Ignatius再次被魔王抓走了(搞不懂他咋这么讨魔王喜欢)…… 这次魔王汲取了上次的教训,把Ignatius关在一个n*m的地牢里,并在地牢的某些地方安装了带 ...

  4. python学习之路-1 python简介及安装方法

    python简介 一种面向对象.解释型计算机程序设计语言,由Guido van Rossum于1989年发明,第一个公开发行版发行于1991年. 目前最新版本为3.5.1,发布于2015年12月07日 ...

  5. JS~重写alter与confirm,让它们变成fancybox风格

    插件与系统命令 对于很多JS弹框插件来说,都提供了alter,confirm等功能,如fancybox,Boxy等插件,今天来介绍一下如何将系统的alter和confirm替换成指定插件的alter和 ...

  6. 一般处理程序、ASP.NET核心知识(5)--转载

    初窥 1.新建一个一般处理程序 新建一个一般处理程序 2.看看里头的代码 public class MyHandler : IHttpHandler { public void ProcessRequ ...

  7. HTML与CSS入门——第三章 理解HTML和XHTML的关系

    知识点: 1.以HTML创建一个简单网页的方法 2.包含每个网页必须有的所有HTML标签的方法 3.用段落和换行组织页面的方法 4.用标题组织内容的方法 5.HTML.XML.XHTML和HTML5之 ...

  8. php使用session来保存用户登录信息

    php使用session来保存用户登录信息 使用session保存页面登录信息 1.数据库连接配置页面:connectvars.php <?php //数据库的位置 define('DB_HOS ...

  9. asp.net repeater控件操作

    Repeater控件和DataList控件,可以用来一次显示一组数据项.比如,可以用它们显示一个数据表中的所有行. Repeater控件完全由模板驱动,提供了最大的灵活性,可以任意设置它的输出格式. ...

  10. C++服务器设计(三):多线程模型设计

    多线程探讨 如今大多数CPU都具有多个核心,为了最大程度的发挥多核处理器的效能,提高服务器的并发性,保证系统对于多线程的支持是十分必要的.我们在之前的设计都是基于单线程而言,在此章我们将对系统进行改进 ...