# [LeetCode] 211. Add and Search Word - Data structure design

## Problem

Design a data structure that supports the following two operations:

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:

search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.

## Solution

``````
class WordDictionary {
public class TrieNode {
public TrieNode[] children = new TrieNode[26];
public boolean isWord = false;
}

TrieNode root = new TrieNode();

TrieNode node = root;
for (char ch: word.toCharArray()) {
if (node.children[ch-'a'] == null) {
node.children[ch-'a'] = new TrieNode();
}
node = node.children[ch-'a'];
}
node.isWord = true;
}

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

private boolean helper(String word, int start, TrieNode node) {
if (start == word.length()) return node.isWord;
char ch = word.charAt(start);
if (ch == '.') {
for (int i = 0; i < 26; i++) {
if (node.children[i] != null && helper(word, start+1, node.children[i])) {
return true;
}
}
} else {
return node.children[ch-'a'] != null && helper(word, start+1, node.children[ch-'a']);
}
return false;
}
}
``````