# LeetCode 211.添加与搜索单词(数据结构设计)

📖Blog ：《LeetCode 211.添加与搜索单词(数据结构设计) - JavaScript》

void addWord(word)
bool search(word)


search(word) 可以搜索文字或正则表达式字符串，字符串只包含字母 .a-z. 可以表示任何一个字母。

addWord("bad")
search("b..") -> true


## 解法 1: 巧妙的正则表达式

# ac地址: https://leetcode-cn.com/problems/add-and-search-word-data-structure-design/

from re import search

class WordDictionary:

def __init__(self):
"""
"""
self.words = '#'

def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
self.words += (word + '#')

def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
return bool(search('#' + word + '#', self.words))


## 解法 2: 字典树（Trie）+ DFS

// ac地址: https://leetcode-cn.com/problems/add-and-search-word-data-structure-design/

var TrieNode = function() {
this.next = {};
this.isEnd = false;
};

/**
* Initialize your data structure here.
*/
var WordDictionary = function() {
this.root = new TrieNode();
};

/**
* @param {string} word
* @return {void}
*/
if (!word.length) return;

let node = this.root;
for (let i = 0; i < word.length; ++i) {
if (!node.next[word[i]]) {
node.next[word[i]] = new TrieNode();
}
node = node.next[word[i]];
}
node.isEnd = true;
};

/**
* @param {string} word
* @return {boolean}
*/
WordDictionary.prototype.search = function(word) {
if (!word.length) return false;

return this.dfs(this.root, word);
};

/**
* @param {TrieNode} root
* @param {string} word
* @return {boolean}
*/
WordDictionary.prototype.dfs = function(root, word) {
const length = word.length;
let node = root;
for (let i = 0; i < length; ++i) {
const ch = word[i];
// 若是通配符，则尝试遍历所有的情况(DFS)
if (ch === ".") {
const keys = Reflect.ownKeys(node.next);
for (const key of keys) {
const found = this.dfs(node.next[key], word.slice(i + 1));
if (found) return true;
}
return false;
}

if (!node.next[ch]) {
return false;
}
node = node.next[ch];
}
return node.isEnd;
};


## 更多资料

posted @ 2020-03-08 00:12  心谭小站  阅读(289)  评论(0编辑  收藏  举报