summary:
construct trie | dfs | classify and discuss
package com.odyssey.app.algorithm.lc.trie;
/**
* @author Dingsheng Huang
* @date 2020/3/18 0:09
*
* 211
* medium
* https://leetcode.com/problems/add-and-search-word-data-structure-design/
*
* 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.
*
*/
class WordDictionary {
class TrieNode {
String word = "";
TrieNode[] children = new TrieNode[26];
}
TrieNode root = new TrieNode();
/** Initialize your data structure here. */
public WordDictionary() {
}
/** Adds a word into the data structure. */
public void addWord(String word) {
char[] chs = word.toCharArray();
TrieNode currNode = this.root;
for (int i = 0; i < chs.length; i++) {
int idx = chs[i] - 'a';
if (currNode.children[idx] == null) {
currNode.children[idx] = new TrieNode();
}
currNode = currNode.children[idx];
}
currNode.word = word;
}
private boolean res = false;
/** 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) {
res = false;
dfs(this.root, word.toCharArray(), 0);
return res;
}
private void dfs(TrieNode currNode, char[] chs, int idx) {
if (currNode == null || idx == chs.length) {
return;
}
// classify
if (chs[idx] == '.') {
if (idx == chs.length - 1) {
// todo optimize
for (TrieNode node : currNode.children) {
if (node != null && node.word.length() > 0) {
res = true;
break;
}
}
} else {
for (TrieNode node : currNode.children) {
dfs(node, chs, idx + 1);
}
}
} else {
if (currNode.children[chs[idx] - 'a'] != null) {
if (idx == chs.length - 1) {
if (currNode.children[chs[idx] - 'a'].word.length() > 0) {
res = true;
}
}
dfs(currNode.children[chs[idx] - 'a'], chs, idx + 1);
}
}
}
}
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary obj = new WordDictionary();
* obj.addWord(word);
* boolean param_2 = obj.search(word);
*/