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
.
public class WordDictionary { public static class TrieNode { TrieNode[] children; boolean isLeaf; public TrieNode() { children = new TrieNode[26]; } } private TrieNode root = new TrieNode(); // Adds a word into the data structure. public void addWord(String word) { if(word == null || word.isEmpty()) return; TrieNode node = root; for(int i=0; i<word.length(); i++) { int j = word.charAt(i)-'a'; if(node.children[j] == null) { node.children[j] = new TrieNode(); } node = node.children[j]; } node.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 search(root, word, 0); } private boolean search(TrieNode node, String word, int start) { if(node == null) return false; if(start == word.length()) return node.isLeaf; for(int i=start; i<word.length(); i++) { char c = word.charAt(i); if(c == '.') { for(int j=0; j<26; j++) { if(search(node.children[j], word, i+1)) return true; } return false; } else { // node = node.children[c-'a']; // if(node == null) return false; return search(node.children[c-'a'], word, i+1); } } return false;//node.isLeaf; } }
相关推荐
* [Data Structure](https://github.com/kamyu104/LeetCode#data-structure) * [Math](https://github.com/kamyu104/LeetCode#math) * [Two Pointers](https://github.com/kamyu104/LeetCode#two-pointers) * [Sort]...
lru缓存leetcode ...数据结构设计https://leetcode.com/problems/add-and-search-word-data-structure-design/ 硬字搜索IIhttps://leetcode.com/problems/word-search-ii/ EasyFind the Difference ...
***o Sum III – Data Structure Design:设计一种数据结构,支持添加和查询两数之和。 4. Valid Palindrome:判断一个字符串是否是回文,忽略大小写和非字母数字字符。 5. Implement strStr():实现字符串查找功能...
3. "Add and Search Word - Data structure design"(添加和搜索单词 - 数据结构设计):这个问题涉及构建一个字典树,并结合LRU缓存进行搜索优化。 在"python-leetcode-master"这个压缩包中,很可能包含了一个或多...
leetcode 推前当前问题 5 从 9 月 9 日到 12 月 9 日,按类型。 100 个主题和 Google。 力码 Leetcode 题目汇总 分类 1、求和问题 1.1 (1) Two Sum 1.2 (15) 3 Sum 1.3 (18) 4 Sum 1.4 (454) 4 Sum II 1.5 (167) Two...
6. **Add and Search Word - Data structure design** (Medium): 在一个前缀树结构中添加单词并搜索。这扩展了 Trie 的功能,包括在现有结构中搜索子字符串。 7. **Word Search II** (Hard): 实现二维网格中的单词...
***o Sum III – Data Structure Design:此问题需要设计数据结构以快速判断是否存在两数和为特定值。 4. Valid Palindrome:判断一个字符串是否为回文字符串,涉及到字符串的遍历和比较。 5. Implement strStr():...