Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // package whatever; // don't place package name!
- import java.util.*;
- class MyCode {
- public static void main (String[] args) {
- //Given an input list of words, design autocomplete function
- //to return list of words when given an input prefix
- String[] words = {"car","camp","catheter","cart","cat","crab","apple","ball","boy","bolster"};
- Trie trie = new Trie();
- for(String word: words) trie.addWord(word);
- System.out.println(trie.autocomplete(""));
- }
- }
- class TrieNode {
- char data;
- boolean endWord;
- HashMap<Character, TrieNode> children;
- public TrieNode(char val){
- this.data = val;
- this.endWord = false;
- this.children = new HashMap<>();
- }
- }
- class Trie {
- TrieNode root;
- public Trie(){
- this.root = new TrieNode(Character.MIN_VALUE); //'\u0000'
- }
- public void addWord(String word) {
- //Create pointer starting root trienode
- TrieNode curr = this.root;
- HashMap<Character, TrieNode> currChildren;
- //Loop characters of word and inserting new node for each into trie
- for(Character ch: word.toCharArray()) {
- currChildren = curr.children;
- if(!currChildren.containsKey(ch)) {
- currChildren.put(ch, new TrieNode(ch));
- }
- //Move curr node pointer to child node associated with child char
- curr = currChildren.get(ch);
- }
- curr.endWord = true;
- }
- private TrieNode getPrefixEndNode(String prefix) {
- //Create pointer starting root trienode
- TrieNode curr = this.root;
- HashMap<Character, TrieNode> currChildren;
- //Loop characters of word and inserting new node for each into trie
- for(Character ch: prefix.toCharArray()) {
- currChildren = curr.children;
- if(!currChildren.containsKey(ch)) {
- return null;
- }
- //Move curr node pointer to child node associated with child char
- curr = currChildren.get(ch);
- }
- return curr;
- }
- public ArrayList<String> autocomplete(String prefix) {
- TrieNode prefixEndNode = getPrefixEndNode(prefix);
- ArrayList<String> result = new ArrayList<>();
- if(prefixEndNode != null) {
- //DFS
- dfs(prefix, prefixEndNode, result);
- }
- return result;
- }
- private void dfs(String currPrefix, TrieNode currNode, ArrayList<String> result) {
- if(currNode.endWord) {
- result.add(currPrefix);
- }
- for(TrieNode child: currNode.children.values()) {
- dfs(currPrefix+child.data, child, result);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement