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. android开发中经常遇到的问题汇总

    大家都在为项目开发成功而喜悦,但可不知成功的路上是会经常出错的,下面是我碰到的一些错误集合! [错误信息] [2011-01-19 16:39:10 - ApiDemos] WARNING: Appl ...

  2. JVM学习总结一——内存模型

    JVM是java知识体系的基石之一,任何一个java程序的运行,都要借助于他.或许对于我这种初级程序员而言,工作中很少有必要刻意去关注JVM,然而如果能对这块知识有所了解,就能够更清晰的明白程序的运行 ...

  3. Go时间戳和日期字符串的相互转换

    Go语言中,获取时间戳用time.Now().Unix(),格式化时间用t.Format,解析时间用time.Parse. 看实例代码: package main import ( "fmt ...

  4. sharepoint 2010 找不到搜索不到ad里的用户

    前提条件: 1.这个用户是在ad中存在的. 2.这个用户也同步到了userprofile中. 问题现象: 在sharepoint的人员选择器中,搜索不到已经添加的用户. 可能原因: 1.有人说需要将 ...

  5. 关于VS2010“ADO.NET Entity Data Model模板丢失或者添加失败问题

    我最近在安装vs2010后,添加ADO.NET Entity 实体时发现,我的新建项里面并没有这个实体模型,后来我就在博问里面发表了问题,请求大家帮忙解决,悲剧的是少有人回应啊,呵呵,不过我还是在网上 ...

  6. java提供了native2ascii工具

    可以使用这个工具,把中文编码称为ascii码 在命令行输入native2ascii 输入中文 得到数据

  7. 20145103《java程序设计》第4周学习总结

    20145103 <Java程序设计>第4周学习总结 教材学习内容总结 继承 继承共同行为 ·继承基本上就是避免多个类间重复定义共同行为. ·继承的三个好处:减少代码冗余:维护变得简单:扩 ...

  8. IOS常用加密Encryption

    NSString+Encryption.h // // NSString+Encryption.h // haochang // // Created by Administrator on 14-4 ...

  9. HashMap优雅的初始化方式以及引申

    小记 相信很多人和笔者一样,经常会做一些数组的初始化工作,也肯定会经常用到集合类.假如我现在要初始化一个String类型的数组,可以很方便的使用如下代码: String [] strs = {&quo ...

  10. Incorrect string value: '\xF0\xA1\xA1\x92' for column 'herst' at row 1

    Incorrect string value: '\xF0\xA1\xA1\x92' for column 'herst' at row 1[转] 1.一般来说MySQL(小于5.5.3)字符集设置为 ...