import
java.util.HashMap;
public
class
Trie {
boolean
isEndOfWord;
HashMap<Character, Trie> map;
static
Trie getNewTrieNode() {
Trie node =
new
Trie();
node.isEndOfWord =
false
;
node.map =
new
HashMap<>();
return
node;
}
static
void
insert(Trie root, String str) {
Trie temp = root;
for
(
int
i =
0
; i < str.length(); i++) {
char
x = str.charAt(i);
if
(!temp.map.containsKey(x))
temp.map.put(x, getNewTrieNode());
temp = temp.map.get(x);
}
temp.isEndOfWord =
true
;
}
static
boolean
search(Trie root, String str) {
if
(root ==
null
)
return
false
;
Trie temp = root;
for
(
int
i =
0
; i < str.length(); i++) {
if
(!temp.map.containsKey(str.charAt(i)))
return
false
;
temp = temp.map.get(str.charAt(i));
}
return
temp.isEndOfWord;
}
public
static
void
main(String[] args) {
Trie root = getNewTrieNode();
insert(root,
"geeks"
);
System.out.print(search(root,
"geeks"
) +
" "
);
insert(root,
"for"
);
System.out.print(search(root,
"for"
) +
" "
);
System.out.print(search(root,
"geekk"
) +
" "
);
insert(root,
"gee"
);
System.out.print(search(root,
"gee"
) +
" "
);
insert(root,
"science"
);
System.out.println(search(root,
"science"
));
insert(root,
"scienc"
);
System.out.println(search(root,
"scienc"
));
}
}