https://leetcode.com/problems/add-and-search-word-data-structure-design/

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.

解题思路:

这题实际上是 Implement Trie (Prefix Tree) 的follow-up。有了上一题的设计,这题唯一需要解决的,就是search这个方法,当遇到'.'的时候,如何办。

本题的addword()方法中,是没有'.'的,所以Trie树内肯定没有'.'。那么当遇到'.'的时候,只要递归search下一层次的所有子节点,有一个路径里找到,就返回true,否则立刻返回false。

public class WordDictionary {
class TrieNode {
// Initialize your data structure here.
boolean isWord;
Map<Character, TrieNode> next;
public TrieNode() {
next = new HashMap<Character, TrieNode>();
isWord = false;
}
} private TrieNode root; public WordDictionary() {
root = new TrieNode();
} // Adds a word into the data structure.
public void addWord(String word) {
TrieNode cur = root;
for(int i = 0; i < word.length(); i++) {
if(cur.next.get(word.charAt(i)) == null) {
TrieNode next = new TrieNode();
cur.next.put(word.charAt(i), next);
}
cur = cur.next.get(word.charAt(i));
}
cur.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 searchHelper(root, word);
} public boolean searchHelper(TrieNode cur, String word) {
if(cur == null) {
return false;
}
for(int i = 0; i < word.length(); i++) {
if(word.charAt(i) != '.') {
cur = cur.next.get(word.charAt(i));
} else {
for(TrieNode value : cur.next.values()) {
if(searchHelper(value, word.substring(i + 1))) {
return true;
}
}
return false;
}
if(cur == null) {
return false;
}
}
return cur.isWord;
}
} // Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");

2018/6/20 二刷

class TrieNode {
HashMap<Character, TrieNode> node;
boolean isWord; public TrieNode() {
node = new HashMap<Character, TrieNode>();
isWord = false;
}
} public class WordDictionary { /** Initialize your data structure here. */
public WordDictionary() {
root = new TrieNode();
} /** Adds a word into the data structure. */
public void addWord(String word) {
TrieNode cur = root;
for (int i = 0; i < word.length(); i++) {
if (!cur.node.containsKey(word.charAt(i))) {
TrieNode node = new TrieNode();
cur.node.put(word.charAt(i), node);
}
cur = cur.node.get(word.charAt(i));
}
cur.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 searchHelper(root, word);
} public boolean searchHelper(TrieNode cur, String word) {
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == '.') {
// 这里是所有都没找到才返回false,不能直接return searchHelper(cur.node.get(key), word.substring(i + 1))
for (Character key : cur.node.keySet()) {
if (searchHelper(cur.node.get(key), word.substring(i + 1))) {
return true;
}
}
return false;
}
if (!cur.node.containsKey(word.charAt(i))) {
return false;
}
cur = cur.node.get(word.charAt(i));
}
return cur.isWord;
} private TrieNode root;
} /**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/

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) ...

  10. [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计

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

随机推荐

  1. netfilter

    http://jingyan.baidu.com/article/642c9d3415d2c9644a46f7c6.html http://blog.csdn.net/zhangskd/article ...

  2. FTP上传文件夹

    文件上传类 using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; usi ...

  3. python-day3-集合

    集合的特性:无序性,唯一性,可嵌套性 1 #创建集合方式 2 s1={11,22}# 直接创建 3 s2=set()#创建空集合 4 s3=set([111,222,333])#转换为集合 1 #集合 ...

  4. Byte measurements

  5. git manual

    git init                                                  # 初始化本地git仓库(创建新仓库) git config --global us ...

  6. poj 1386 Play on Words 有向欧拉回路

    题目链接:http://poj.org/problem?id=1386 Some of the secret doors contain a very interesting word puzzle. ...

  7. poj 1300 Door Man 欧拉回路

    题目链接:http://poj.org/problem?id=1300 You are a butler in a large mansion. This mansion has so many ro ...

  8. Leetcode#174 Dungeon Game

    原题地址 典型的地图寻路问题 如何计算当前位置最少需要多少体力呢?无非就是在向下走或向右走两个方案里做出选择罢了. 如果向下走,看看当前位置能提供多少体力(如果是恶魔就是负数,如果是草药就是正数),如 ...

  9. frequentism-and-bayesianism-chs-ii

    frequentism-and-bayesianism-chs-ii 频率主义 vs 贝叶斯主义 II:当结果不同时   这个notebook出自Pythonic Perambulations的博文  ...

  10. 《JavaScript高级程序设计》

    第二章在html中使用Javascript2.1<script>在使用<script>嵌入JS代码时,不要再代码中的任何地方出现"</script>&qu ...