题目:

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.

click to show hint.

You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.

链接: http://leetcode.com/problems/add-and-search-word-data-structure-design/

题解:

设计一个Data Structure来search和add单词。这道题我们又可以用一个R-Way Trie来完成。 像JQuery里面的Auto-complete功能其实就可以用R-Way Trie based method来设计和编程。注意当字符为"."的时候我们要loop当前节点的全部26个子节点,这里要用一个DFS。

Time Complexity - O(n),  Space Complextiy - O(26n)。

public class WordDictionary {
private TrieNode root = new TrieNode(); private class TrieNode {
private final int R = 26; // radix = 26
public TrieNode[] next;
public boolean isWord; public TrieNode() {
next = new TrieNode[R];
}
} // Adds a word into the data structure.
public void addWord(String word) {
if(word == null || word.length() == 0)
return;
TrieNode node = root;
int d = 0; while(d < word.length()) {
char c = word.charAt(d);
if(node.next[c - 'a'] == null)
node.next[c - 'a'] = new TrieNode();
node = node.next[c - 'a'];
d++;
} node.isWord = 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) {
if(word == null || word.length() == 0)
return false;
TrieNode node = root;
int d = 0; return search(node, word, 0);
} private boolean search(TrieNode node, String word, int d) {
if(node == null)
return false;
if(d == word.length())
return node.isWord;
char c = word.charAt(d);
if(c == '.') {
for(TrieNode child : node.next) {
if(child != null && search(child, word, d + 1))
return true;
}
return false;
} else {
return search(node.next[c - 'a'], word, d + 1);
}
}
} // Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");

二刷:

方法和一刷一样,主要使用Trie。addWord的时候还是使用和Trie的insert一样的的代码。 Search的时候因为有一个通配符'.',所以我们要用dfs搜索节点的26个子节点。

假如使用Python的话可以不用Trie,直接用dict来做。

Java:

Time Complexity:  addWord - O(L) ,   search - O(26L),  Space Complexity - O(26L)   这里 L是单词的平均长度。

public class WordDictionary {
TrieNode root = new TrieNode();
// Adds a word into the data structure.
public void addWord(String word) {
if (word == null) return;
TrieNode node = this.root;
int d = 0;
while (d < word.length()) {
int index = word.charAt(d) - 'a';
if (node.next[index] == null) node.next[index] = new TrieNode();
node = node.next[index];
d++;
}
node.isWord = 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 search(word, root, 0);
} private boolean search(String word, TrieNode node, int depth) {
if (node == null) return false;
if (depth == word.length()) return node.isWord;
char c = word.charAt(depth);
if (c != '.') {
return search(word, node.next[c - 'a'], depth + 1);
} else {
for (TrieNode nextNode : node.next) {
if (search(word, nextNode, depth + 1)) return true;
}
return false;
}
} private class TrieNode {
TrieNode[] next;
int R = 26;
boolean isWord; public TrieNode() {
this.next = new TrieNode[R];
}
}
} // Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");

Reference:

https://leetcode.com/discuss/35878/java-hashmap-backed-trie

https://leetcode.com/discuss/35928/my-simple-and-clean-java-code

https://leetcode.com/problems/implement-trie-prefix-tree/

https://leetcode.com/discuss/69963/python-168ms-beat-100%25-solution

211. Add and Search Word - Data structure design的更多相关文章

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

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

  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】211. Add and Search Word - Data structure design

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

  4. (*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 ...

  5. 【LeetCode】211. Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,211,搜索单词,前缀树,字典树 ...

  6. Java for LeetCode 211 Add and Search Word - Data structure design

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

  7. leetcode@ [211] Add and Search Word - Data structure design

    https://leetcode.com/problems/add-and-search-word-data-structure-design/ 本题是在Trie树进行dfs+backtracking ...

  8. [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 ...

  9. [leetcode trie]211. Add and Search Word - Data structure design

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

随机推荐

  1. 一次GC问题定位

    同事有段代码执行时间过长,需要进行优化, Hashmultimap<Int,Bean> map = ...; for (400w*96) { // 计算过程 Bean = doComput ...

  2. C语言中格式化输出的转换说明的fldwidth和precision解析

    首先说什么是C语言的格式化输出,就是printf和它的几个变种(grep -E "v?(sn|s|f)printf").像这些函数都有一个参数format,format中可以加点转 ...

  3. 解决Scala异常处理java.lang.OutOfMemoryError: Java heap space error

    需求:百万.千万.4千万级日志对设备进行除重环境:设备内存64G,scala单机版运行shell文件日志:20G 48000000.log4.0G 10000000.log396M 1000000.l ...

  4. 锋利的jquery-事件和动画

    1 注册事件的触发时机 在jquery中,$(window).load(function(){}) 注册在window下的事件等待页面所有资源加载完成(包括dome树的加载和图片视频的资源的加载) $ ...

  5. 【转】给Winform的button等控件添加快捷键

    ref: http://blog.sina.com.cn/s/blog_4cb9953f0100cy4z.html 第一种:Alt + *(按钮快捷键) 在大家给button.label.menuSt ...

  6. C#让TopMost窗体弹出并置顶层但不获取当前输入焦点的终极办法

    为了使程序在弹出窗口时置顶层且不获取系统输入焦点,避免影响用户当前的操作,来电通来电弹屏软件尝试过N多种办法,例如:弹出前保存当前焦点窗口句柄,弹出时因为使用TopMost系统默认将焦点交给了弹出窗口 ...

  7. mouseenter 事件,固定右侧客服特效

    不论鼠标指针穿过被选元素或其子元素,都会触发 mouseover 事件. 只有在鼠标指针穿过被选元素时,才会触发 mouseenter 事件. 当鼠标指针离开元素时,会发生 mouseleave 事件 ...

  8. Ajax 之【文件上传】

    // 前台 var formData = new FormData(); var file = document.getElementById('myFile').files[0]; formData ...

  9. php Zend Opcache,xcache,eAccelerator缓存优化详解及对比

    XCACHE XCache 是一个开源的 opcode 缓存器/优化器, 这意味着他能够提高您服务器上的 PHP 性能. 他通过把编译 PHP 后的数据缓冲到共享内存从而避免重复的编译过程, 能够直接 ...

  10. 【生活】已经从官网购买iPad,单独购买AppleCare+服务

    1 什么是AppleCare+服务 从苹果官网购买的硬件产品如ipad.iphone和MacBook等,官网承诺的保修期限是一年.AppleCare+是水果公司推出的一种保修服务,最大的特点就是将保修 ...