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. What’s the difference between an interface and an abstract class in Java?

    原文 What’s the difference between an interface and an abstract class in Java? It’s best to start answ ...

  2. LinQ to SQL 查询

    LINQ to SQL 是将对象关系映射到.NET框架中的一种实现.它可以将关系数据库映射为.NET Framework中的一些类. 然后,开发人员就可以通过使用 LINQ to SQL对数据库中的数 ...

  3. DirectX 初始化DirectX(手写和红龙书里面的方式)

    上次介绍了如何初始化Direct3D,这次手写一次初始化代码,都是一样的方式不过看起来整洁一点. 创建一个Win32空项目添加一个空类增加以下代码即可. #include "CreateDe ...

  4. python标准库 difflib-比较序列

    # -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' #difflib比较序列 #版本2.1及之后 #作用:包含一些用来计 ...

  5. jQuery插件Jeditable的使用(Struts2处理)

        Jeditable - Edit In Place Plugin For jQuery,是一款JQuery就地编辑插件.也就是在页面直接点击需要编辑的内容,就会自动变成文本框进行编辑.它的官方 ...

  6. 01我为什么学Unity3d

    首发于游戏蛮牛论坛&&我的CSDN博客:http://blog.csdn.net/wowkk/article/details/18571055 转载请说明出处.谢谢. 本人现大学生,带 ...

  7. 虚拟Linux 訪问win7共享文件夹方法

    虚拟机訪问win7的共享文件夹 首先安装增强功能,这个不用多说 再者选择菜单中的设备->共享目录,设置为固定分配和自己主动挂载 在终端敲入命令df:发现有自己创建共享的文件夹 然后运行例如以下命 ...

  8. Sql Server 函数的操作实例!(执行多条语句,返回Select查询后的临时表)

    Sql Server 函数的操作实例!(执行多条语句,返回Select查询后的临时表) SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ==== ...

  9. php的一些特殊用法

    php ruturn的另一个用法 database.php <?php return array ( 'hostname' => 'localhost', 'database' => ...

  10. 调用[[UIDevice currentDevice] userInterfaceIdiom]==UIUserInterfaceIdiomPad判断设备

    将模拟器改为Ipad时,调用[[UIDevice currentDevice] userInterfaceIdiom]==UIUserInterfaceIdiomPad判断设备是否为Ipad,但程序并 ...