[LeetCode] 211. 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.
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
.
208. Implement Trie (Prefix Tree) 的拓展,字典树的数据结构设计应用。
Java: Using backtrack to check each character of word to search.
public class WordDictionary {
public class TrieNode {
public TrieNode[] children = new TrieNode[26];
public String item = "";
} private TrieNode root = new TrieNode(); public void addWord(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.children[c - 'a'] == null) {
node.children[c - 'a'] = new TrieNode();
}
node = node.children[c - 'a'];
}
node.item = word;
} public boolean search(String word) {
return match(word.toCharArray(), 0, root);
} private boolean match(char[] chs, int k, TrieNode node) {
if (k == chs.length) return !node.item.equals("");
if (chs[k] != '.') {
return node.children[chs[k] - 'a'] != null && match(chs, k + 1, node.children[chs[k] - 'a']);
} else {
for (int i = 0; i < node.children.length; i++) {
if (node.children[i] != null) {
if (match(chs, k + 1, node.children[i])) {
return true;
}
}
}
}
return false;
}
}
Python:
class TrieNode:
# Initialize your data structure here.
def __init__(self):
self.is_string = False
self.leaves = {} class WordDictionary:
def __init__(self):
self.root = TrieNode() # @param {string} word
# @return {void}
# Adds a word into the data structure.
def addWord(self, word):
curr = self.root
for c in word:
if c not in curr.leaves:
curr.leaves[c] = TrieNode()
curr = curr.leaves[c]
curr.is_string = True # @param {string} word
# @return {boolean}
# Returns if the word is in the data structure. A word could
# contain the dot character '.' to represent any one letter.
def search(self, word):
return self.searchHelper(word, 0, self.root) def searchHelper(self, word, start, curr):
if start == len(word):
return curr.is_string
if word[start] in curr.leaves:
return self.searchHelper(word, start+1, curr.leaves[word[start]])
elif word[start] == '.':
for c in curr.leaves:
if self.searchHelper(word, start+1, curr.leaves[c]):
return True return False
C++:
class WordDictionary {
public:
struct TrieNode {
public:
TrieNode *child[26];
bool isWord;
TrieNode() : isWord(false) {
for (auto &a : child) a = NULL;
}
}; WordDictionary() {
root = new TrieNode();
} // Adds a word into the data structure.
void addWord(string word) {
TrieNode *p = root;
for (auto &a : word) {
int i = a - 'a';
if (!p->child[i]) p->child[i] = new TrieNode();
p = p->child[i];
}
p->isWord = true;
} // Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
bool search(string word) {
return searchWord(word, root, 0);
} bool searchWord(string &word, TrieNode *p, int i) {
if (i == word.size()) return p->isWord;
if (word[i] == '.') {
for (auto &a : p->child) {
if (a && searchWord(word, a, i + 1)) return true;
}
return false;
} else {
return p->child[word[i] - 'a'] && searchWord(word, p->child[word[i] - 'a'], i + 1);
}
} private:
TrieNode *root;
};
类似题目:
[LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)
All LeetCode Questions List 题目汇总
[LeetCode] 211. Add and Search Word - Data structure design 添加和查找单词-数据结构设计的更多相关文章
- 【LeetCode】211. Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,211,搜索单词,前缀树,字典树 ...
- [LeetCode] Add and Search Word - Data structure design 添加和查找单词-数据结构设计
Design a data structure that supports the following two operations: void addWord(word) bool search(w ...
- 211 Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计
设计一个支持以下两个操作的数据结构:void addWord(word)bool search(word)search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z . ...
- Leetcode211. Add and Search Word - Data structure design 添加与搜索单词 - 数据结构设计
设计一个支持以下两种操作的数据结构: void addWord(word) bool search(word) search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a- ...
- [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 ...
- 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 ...
- (*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 ...
- leetcode@ [211] Add and Search Word - Data structure design
https://leetcode.com/problems/add-and-search-word-data-structure-design/ 本题是在Trie树进行dfs+backtracking ...
- leetcode 211. Add and Search Word - Data structure design Trie树
题目链接 写一个数据结构, 支持两种操作. 加入一个字符串, 查找一个字符串是否存在.查找的时候, '.'可以代表任意一个字符. 显然是Trie树, 添加就是正常的添加, 查找的时候只要dfs查找就可 ...
随机推荐
- python的pandas库读取csv
首先建立test.csv原始数据,内容如下 时间,地点 一月,北京 二月,上海 三月,广东 四月,深圳 五月,河南 六月,郑州 七月,新密 八月,大连 九月,盘锦 十月,沈阳 十一月,武汉 十二月,南 ...
- java调用c++库
c++ 写的库 jni封装一层 才可以给 java调用
- 树莓派安装C#运行环境
一. 安装mono ARMv6(一代 Raspberry Pi B+) : http://yunpan.cn/cw6NYzXkD9kHq 访问密码 63ae ARMv7(二代 Raspberry Pi ...
- phantomJS+Python 隐形浏览器
phantomjs解压后,把文件夹bin中的phantomjs.exe移到python文件夹中的Scripts中 实例: from selenium import webdriver driver = ...
- Spark 基础 —— 创建 DataFrame 的三种方式
1.自定义 schema(Rdd[Row] => DataSet[Row]) import org.apache.spark.sql.types._ val peopleRDD = spark. ...
- Sliding Window Matrix Maximum
Description Given an array of n * m matrix, and a moving matrix window (size k * k), move the window ...
- [CSS3] Use media query to split css files and Dark mode (prefers-color-scheme: dark)
Dark Mode: :root { --text-color: #000; --background-color: #fff; } body { color: var(--text-color); ...
- [Javascript] Check Promise is Promise
const isPromise = obj => Boolean(obj) && typeof obj.then === 'function'; This can be a to ...
- jupyter Notebook 设置密码
由于服务器关闭了图形界面 所以在服务器上安装Jupyter Notebook 随后本机web访问,利用本机的显卡可以执行plt相关图形命令 本次介绍如何设置Jupyter Notebook的密码设定 ...
- JavaScript基础05——严格模式
严格模式: 除了正常运行模式,ECMAscript5添加了第二种运行模式:“严格模式”(strict mode).顾名思义,这种模式是的Javascript在更严格的条件下运行. 严格模式的作用: 1 ...