File tree Expand file tree Collapse file tree 1 file changed +54
-0
lines changed
design-add-and-search-words-data-structure Expand file tree Collapse file tree 1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change 1+ class WordDictionary {
2+ private static class TrieNode {
3+ boolean isEnd ;
4+ Map <Character , TrieNode > children ;
5+
6+ TrieNode () {
7+ this .isEnd = false ;
8+ this .children = new HashMap <>();
9+ }
10+ }
11+
12+ private final TrieNode root ;
13+
14+ public WordDictionary () {
15+ root = new TrieNode ();
16+ }
17+
18+ public void addWord (String word ) {
19+ TrieNode node = root ;
20+ for (char ch : word .toCharArray ()) {
21+ node .children .putIfAbsent (ch , new TrieNode ());
22+ node = node .children .get (ch );
23+ }
24+ node .isEnd = true ;
25+ }
26+
27+ public boolean search (String word ) {
28+ return dfs (root , word , 0 );
29+ }
30+
31+ private boolean dfs (TrieNode node , String word , int index ) {
32+ if (index == word .length ()) {
33+ return node .isEnd ;
34+ }
35+
36+ char ch = word .charAt (index );
37+ if (ch == '.' ) {
38+ for (TrieNode child : node .children .values ()) {
39+ if (dfs (child , word , index + 1 )) {
40+ return true ;
41+ }
42+ }
43+ return false ;
44+ }
45+
46+ TrieNode next = node .children .get (ch );
47+ if (next == null ) {
48+ return false ;
49+ }
50+
51+ return dfs (next , word , index + 1 );
52+ }
53+ }
54+
You can’t perform that action at this time.
0 commit comments