Skip to content

Instantly share code, notes, and snippets.

@iankit3
Created September 8, 2020 19:09
Show Gist options
  • Save iankit3/2e09a46c291cca313dd388b7bc88ce45 to your computer and use it in GitHub Desktop.
Save iankit3/2e09a46c291cca313dd388b7bc88ce45 to your computer and use it in GitHub Desktop.
An Trie implementation
import java.util.*;
class Trie {
public class TrieNode {
public Map<Character, TrieNode> map;
public boolean isEndOfWord;
TrieNode(boolean isEndOfWord) {
this.map = new HashMap<>();
this.isEndOfWord = isEndOfWord;
}
}
public TrieNode root = new TrieNode(false);
public TrieNode insertChar(TrieNode node, char c, boolean isEndOfWord) {
if (!node.map.containsKey(c)) {
node.map.put(c, new TrieNode(isEndOfWord));
}
return node.map.get(c);
}
public void insert(String s) {
TrieNode node = root;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
node = insertChar(node, c, i == (s.length()-1) );
}
}
public static void main(String[] args) {
Solution s = new Solution();
s.insert("abcd");
s.insert("bcd");
System.out.println(s.root.map.get('b').map.get('c').map.get('d').isEndOfWord);
}
}
@iankit3
Copy link
Author

iankit3 commented Sep 8, 2020

And delete

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment