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. SEO的URL如何优化才是最佳

    原文地址:http://www.chinaz.com/web/2007/0413/6841.shtml 很多人都知道URL对SEO的重要之处,但是很多站点却忽略了站点的路径优化.今天本人在这里写几点关 ...

  2. KDTree详解及java实现

    本文内容基于An introductory tutoril on kd-trees 1.KDTree介绍 KDTree根据m维空间中的数据集D构建的二叉树,能加快常用于最近邻查找(在加快k-means ...

  3. Java中ThreadLocal无锁化线程封闭实现原理

    虽然现在可以说很多程序员会用ThreadLocal,但是我相信大多数程序员还不知道ThreadLocal,而使用ThreadLocal的程序员大多只是知道其然而不知其所以然,因此,使用ThreadLo ...

  4. pyqt QTableView例子学习

    # -*- coding: utf-8 -*- # python:2.x __author__ = 'Administrator' from PyQt4.QtGui import  * from Py ...

  5. PC-CSS-分隔线

    单个标签实现分隔线: 点此查看实例展示 .demo_line_01{ padding: 0 20px 0; margin: 20px 0; line-height: 1px; border-left: ...

  6. java 面向过程实现万年历

    public class Test { /** * @param args */ public static void main(String[] args) { // TODO Auto-gener ...

  7. xcode 执行时模拟器不可选的问题

    好久没写博客了,上一次是什么时候都想不起来了. 之前总认为脑袋记住了,用过了就能够了,干嘛要写博客,简直浪费时间.事实上没事写写博客优点还是挺多的.这样既能够对自己用过的和学到的东西做一个总结,也能提 ...

  8. HDU 1863:畅通project(带权值的并查集)

    畅通project Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total ...

  9. [SQL学习笔记][用exists代替全称量词 ]

    学习sql的必经问题. 学生表student (id学号 Sname姓名 Sdept所在系) 课程表Course (crscode课程号 name课程名) 学生选课表transcript (studi ...

  10. 用CSS画五角星

    <!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8" ...