Skip to content

211. Design Add and Search Words Data Structure 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
struct TrieNode {
  vector<shared_ptr<TrieNode>> children;
  bool isWord = false;
  TrieNode() : children(26) {}
};

class WordDictionary {
 public:
  void addWord(const string& word) {
    auto node = root;
    for (const char c : word) {
      const int i = c - 'a';
      if (!node->children[i])
        node->children[i] = make_shared<TrieNode>();
      node = node->children[i];
    }
    node->isWord = true;
  }

  bool search(const string& word) {
    return dfs(word, 0, root);
  }

 private:
  shared_ptr<TrieNode> root = make_shared<TrieNode>();

  bool dfs(const string& word, int s, shared_ptr<TrieNode> node) {
    if (s == word.length())
      return node->isWord;
    if (word[s] != '.') {
      auto next = node->children[word[s] - 'a'];
      return next ? dfs(word, s + 1, next) : false;
    }

    // word[s] == '.' -> search all 26 children
    for (int i = 0; i < 26; ++i)
      if (node->children[i] && dfs(word, s + 1, node->children[i]))
        return true;

    return false;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class TrieNode {
  public TrieNode[] children = new TrieNode[26];
  public boolean isWord = false;
}

class WordDictionary {
  public void addWord(String word) {
    TrieNode node = root;
    for (final char c : word.toCharArray()) {
      final int i = c - 'a';
      if (node.children[i] == null)
        node.children[i] = new TrieNode();
      node = node.children[i];
    }
    node.isWord = true;
  }

  public boolean search(String word) {
    return dfs(word, 0, root);
  }

  private TrieNode root = new TrieNode();

  private boolean dfs(String word, int s, TrieNode node) {
    if (s == word.length())
      return node.isWord;
    if (word.charAt(s) != '.') {
      TrieNode next = node.children[word.charAt(s) - 'a'];
      return next == null ? false : dfs(word, s + 1, next);
    }

    // word.charAt(s) == '.' -> search all 26 children
    for (int i = 0; i < 26; ++i)
      if (node.children[i] != null && dfs(word, s + 1, node.children[i]))
        return true;

    return false;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class WordDictionary:
  def __init__(self):
    self.root = {}

  def addWord(self, word: str) -> None:
    node = self.root
    for c in word:
      if c not in node:
        node[c] = {}
      node = node[c]
    node['isWord'] = True

  def search(self, word: str) -> bool:
    return self.dfs(word, 0, self.root)

  def dfs(self, word: str, s: int, node: dict) -> bool:
    if s == len(word):
      return 'isWord' in node
    if word[s] != '.':
      if word[s] in node:
        return self.dfs(word, s + 1, node[word[s]])
      return False

    for c in string.ascii_lowercase:
      if c in node and self.dfs(word, s + 1, node[c]):
        return True

    return False
Back to top