0211. Add and Search Word - Data structure design (M)
阿新 • • 發佈:2020-08-06
Add and Search Word - Data structure design (M)
題目
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
.
題意
設計一個數據結構,支援插入單詞和搜尋單詞兩個操作。其中,搜尋單詞的引數可以是一個包含萬用字元"."的正則。
思路
和 0208. Implement Trie (Prefix Tree) (M) 一樣使用字典樹。不同之處在於當搜尋字元為"."時,要查詢所有出現過的字母。
程式碼實現
Java
class WordDictionary { Node root; /** Initialize your data structure here. */ public WordDictionary() { root = new Node(); } /** Adds a word into the data structure. */ public void addWord(String word) { Node p = root; for (char c : word.toCharArray()) { if (p.children[c - 'a'] == null) { p.children[c - 'a'] = new Node(); } p = p.children[c - 'a']; } p.end = 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(word, 0, root); } private boolean search(String word, int index, Node p) { if (index == word.length()) { return p.end; } char c = word.charAt(index); if (c == '.') { for (Node next : p.children) { if (next != null && search(word, index + 1, next)) { return true; } } return false; } else { return p.children[c - 'a'] != null ? search(word, index + 1, p.children[c - 'a']) : false; } } } class Node { Node[] children = new Node[26]; boolean end; } /** * Your WordDictionary object will be instantiated and called as such: * WordDictionary obj = new WordDictionary(); obj.addWord(word); boolean param_2 * = obj.search(word); */