Created
September 8, 2020 19:09
-
-
Save iankit3/2e09a46c291cca313dd388b7bc88ce45 to your computer and use it in GitHub Desktop.
An Trie implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And delete