题目:

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. 《java编程思想》--多线程基础--Runnable

    一.简单说下Runnable是什么 1.它是一个接口 2.只提供了run方法 3.这个接口提供了一个协议:实现这个接口的类是active的(不必成为Thread的子类) 4.run方法没有返回值 /* ...

  2. MySQ binlog三种模式

    MySQ binlog三种模式及设置方法 1.1 Row Level  行模式 日志中会记录每一行数据被修改的形式,然后在slave端再对相同的数据进行修改 优点:在row level模式下,bin- ...

  3. JQ批量控制form禁用

    <script type="text/javascript" src="http://www.joy-city.com.cn/templets/default/sc ...

  4. Eclipse中将项目导出jar包,以及转化成exe的方法

    Eclipse中将项目导出jar包,以及转化成exe的方法 http://wenku.baidu.com/view/385597f07c1cfad6195fa7c6.html

  5. win7 vs2008 激活

    参考:http://www.cnblogs.com/wgx0428/archive/2012/08/07/2627380.html win7需要管理员方式运行软件,才能看到输入框 软件:http:// ...

  6. tortoiseGit的SHH秘钥设置

    tortoiseGit如果安装时使用默认的putty方式,因为putty的秘钥格式和SSH的不一样,所以要使用自带的工具重新生成一次秘钥. 具体的方式是:用puttyGen工具来生成公钥和秘钥,公钥( ...

  7. realloc() 用法详解

    原型:extern void *realloc(void *mem_address, unsigned int newsize); 语法:指针名=(数据类型*)realloc(要改变内存大小的指针名, ...

  8. Beaglebone Back学习三(开发环境搭建)

    开发环境搭建 1 Ubuntu环境搭建 2 Window环境搭建 3 开发板环境搭建 1 Ubuntu环境搭建 (1)安装必要的网络工具 samba nfs tftp vmware-tools sam ...

  9. Python+PyQt 数据库基本操作

    Sqlite: 使用Python的sqlite3: 需要注意下commit方式与qt稍有不同 import sqlite3 class DBManager(): def __init__(self): ...

  10. 实现c++的string的split功能

    今天写程序,遇到了一个要实现string.split()这个的一个函数.python里面有,qt里面有,c++里面没有.照着网上抄了一个,放在这里.有需要的时候直接拽过去用,否则老是写了小例子就扔,用 ...