|
| 1 | +// https://leetcode.com/problems/design-add-and-search-words-data-structure |
| 2 | +// S: O(sum |word|_i) |
| 3 | +/* |
| 4 | + trie.add(String word) |
| 5 | + T: O(word) |
| 6 | +
|
| 7 | + trie.contains(String word) |
| 8 | + T: O(26^3 * word) = O(k * word) = O(word) |
| 9 | + */ |
| 10 | +/* |
| 11 | + word_dict.addWord(String word) |
| 12 | + T: O(word) |
| 13 | +
|
| 14 | + word_dict.search(String word) |
| 15 | + T: O(word) |
| 16 | + */ |
| 17 | + |
| 18 | +import java.util.HashSet; |
| 19 | +import java.util.Set; |
| 20 | + |
| 21 | +public class DesignAddAndSearchWordsDataStructure { |
| 22 | + private static final class WordDictionary { |
| 23 | + |
| 24 | + private final Trie trie = new Trie(); |
| 25 | + private final Set<String> words = new HashSet<>(); |
| 26 | + |
| 27 | + public void addWord(String word) { |
| 28 | + words.add(word); |
| 29 | + trie.add(word); |
| 30 | + } |
| 31 | + |
| 32 | + public boolean search(String word) { |
| 33 | + if (!containsDots(word)) return words.contains(word); |
| 34 | + return trie.contains(word); |
| 35 | + } |
| 36 | + |
| 37 | + private boolean containsDots(String word) { |
| 38 | + for (int i = 0 ; i < word.length() ; i++) { |
| 39 | + if (word.charAt(i) == '.') return true; |
| 40 | + } |
| 41 | + return false; |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + private static final class Trie { |
| 46 | + final Trie[] children = new Trie[26]; |
| 47 | + boolean isWord = false; |
| 48 | + |
| 49 | + public void add(String s) { |
| 50 | + add(s, 0); |
| 51 | + } |
| 52 | + |
| 53 | + private void add(String s, int index) { |
| 54 | + if (index == s.length()) { |
| 55 | + isWord = true; |
| 56 | + return; |
| 57 | + } |
| 58 | + char c = s.charAt(index); |
| 59 | + if (children[c - 'a'] == null) children[c - 'a'] = new Trie(); |
| 60 | + children[c - 'a'].add(s, index + 1); |
| 61 | + } |
| 62 | + |
| 63 | + public boolean contains(String s) { |
| 64 | + return contains(s, 0); |
| 65 | + } |
| 66 | + |
| 67 | + private boolean contains(String s, int index) { |
| 68 | + if (index == s.length()) return isWord; |
| 69 | + char character = s.charAt(index); |
| 70 | + if (character != '.') { |
| 71 | + return children[character - 'a'] != null && children[character - 'a'].contains(s, index + 1); |
| 72 | + } |
| 73 | + for (Trie child : children) { |
| 74 | + if (child != null && child.contains(s, index + 1)) { |
| 75 | + return true; |
| 76 | + } |
| 77 | + } |
| 78 | + return false; |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments