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. unix c 06

    文件操作 fcntl-> 复制文件描述符/取文件状态/文件锁 文件一系列函数-> access/chmod/truncate/... 目录操作 相关函数:mkdir/rmdir/telld ...

  2. 发几个速度快可以用的google IP,谷歌IP(转)

    google搜索引擎打不开时的解决办法,谷歌(google)的IP是多少? google IP镜像. 这里搜集了几个经过测试可用的IP,用来在不能域名访问google的时候进行访问,实时更新! 前面几 ...

  3. 独立写作(A or B)

    开头:On contemporary society(一般的背景)/ With the advent of the technologically advanced society (the info ...

  4. obiz

    ofbiz 安装 1. 由 binary 安装: 由 binary 安装非常简单, 以下是安装方法: 下载ofbiz-2.0-beta1-complete.tar.gz, 注意不是ofbiz-2.0- ...

  5. android中的本地定时推送到通知栏

    一.使用系统定义的Notification 以下是使用示例代码: import android.app.Notification; import android.app.NotificationMan ...

  6. js控制html5 audio的暂停、播放、停止

    <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <meta name ...

  7. ASP.NET 后台下载文件方法

    void DownLoadFile(string fileName) { string filePath = Server.MapPath(fileName);//路径 //以字符流的形式下载文件 F ...

  8. Highcharts属性

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  9. IOS开发之程序执行状态更改

    1 前言 上节我们介绍了程序执行的状态,从例子中我们可以发现处理这些状态更改的时候有明确的策略可以遵循,这次我们就来介绍一下. 2 详述 2.1 活动->不活动 使用applicationWil ...

  10. bzoj 2049 Cave 洞穴勘测(LCT)

    转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud 动态树入门题,不需要维护任何信息. 我用的是splay,下标实现的lct. #in ...