题目:

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. Nodejs微信接口

    代码重要部分都已详细注释,test.js为实例,如果启动url请求,那么程序默认对json格式数据友好,如果有特殊需要,请自行修改返回数据的处理格式 大概功能简介为下: this._token 提供t ...

  2. [DevExpress][TreeList]条件隐藏节点CheckBox

    关键代码: /// <summary> /// 隐藏CheckBox /// 说明 /// 在CustomDrawNodeCheckBox事件中使用 /// eg: /// TreeLis ...

  3. HTML5 内联框架iFrame

    由于现在frame和frameset很少使用,已经过时了,已经被div+CSS代替了,所以,这里只是举例说明一下,当下还在使用的内联框架iFrame 所谓的iFrame内联框架,我的理解就是在网页内部 ...

  4. Android:ListView之ViewHolder

    前言 在开发Android应用过程中经常要与列表展示打交道,比如Listview.在使用过程中如果不能正确的进行细节处理那么对性能还是有很大的损耗的. Listview展示内容是通过一个Adapter ...

  5. 在AWS上安装laravel框架

    博客已经迁移到www.imyzf.com,本站不再更新,请谅解! Laravel是现在非常热门的PHP框架,这几天我试着在亚马逊AWS的服务器上安装Laravel,遇到很多问题,最后还是成功了.我的系 ...

  6. 爬虫学习之基于Scrapy的爬虫自动登录

    ###概述 在前面两篇(爬虫学习之基于Scrapy的网络爬虫和爬虫学习之简单的网络爬虫)文章中我们通过两个实际的案例,采用不同的方式进行了内容提取.我们对网络爬虫有了一个比较初级的认识,只要发起请求获 ...

  7. N皇后摆放问题

    Description 在N*N的方格棋盘放置了N个皇后,使得它们不相互攻击(即任意2个皇后不允许处在同一排,同一列,也不允许处在与棋盘边框成45角的斜线上.  你的任务是,对于给定的N,求出有多少种 ...

  8. 【BZOJ3524】 [Poi2014]Couriers

    Description 给一个长度为n的序列a.1≤a[i]≤n.m组询问,每次询问一个区间[l,r],是否存在一个数在[l,r]中出现的次数大于(r-l+1)/2.如果存在,输出这个数,否则输出0. ...

  9. Mapped Statements collection does not contain value for TaskMapper.selectByPrimaryKey

    Mapped Statements collection does not contain value for后面是什么类什么方法之类的: 错误原因有几种: 1.mapper.xml中没有加入name ...

  10. TCP报头

    源端口和目的端口: 各占16位 ,服务相对应的源端口和目的端口. 序列号: 占32位,它的范围在[0~2^32-1],序号随着通信的进行不断的递增,当达到最大值的时候重新回到0在开始递增.TCP是面向 ...