Posts Trie - Introduction - Part 2
Post
Cancel

Trie - Introduction - Part 2

INTRODUCTION TO TRIE - PART 2

Trie Introduction: Part 1

snapshot

Implementation

leetcode

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
public class Trie {
    
    Node root;
    
    class Node{
        boolean isEnd;
        Map<Character, Node> hm;
        Node(Map<Character, Node> hm){
            this.hm = hm;
        }
    }
    
    public Trie() {
        root = new Node(new HashMap<>());
    }
    
    public void insert(String word) {
        
        int n = word.length();
        
        Node temp = root;
        
        //Loop through the string
        for(int i=0; i<n; i++){
            
            //Get the current character
            Character c = Character.valueOf(word.charAt(i));
            
            //Check if the current Node's hashmap contains that character
            if(temp.hm.containsKey(c)){
                //If it contains the character already, go to the next Node. 
                //We need to go to the corresponding Node for the current character which we can get from the HashMap.
                temp = temp.hm.get(c);
            }else{
                //If the character is not present in the HashMap, new a new Node which will act like the next one for the current character.
                temp.hm.put(c, new Node(new HashMap<>()));
                //Once that's is set, go to the next node
                temp = temp.hm.get(c);
            }
            
        }
        
        temp.isEnd = true;
        
    }
    
    public boolean search(String word) {
        
        int n = word.length();
        
        Node temp = root;
        
        //Loop through the word
        for(int i=0; i<n; i++){
            
            //Get the current character
            Character c = Character.valueOf(word.charAt(i));
            
            if(!temp.hm.containsKey(c)){
                return false;
            }else{
                temp = temp.hm.get(c);
            }
            
        }
        //Since we need a complete match and not just prefix, we need to check if isEnd on the current node is true.
        return temp.isEnd;

    }
    
    public boolean startsWith(String prefix) {

        int n = prefix.length();
        
        Node temp = root;
        
        for(int i=0; i<n; i++){
            
            Character c = Character.valueOf(prefix.charAt(i));
            
            if(!temp.hm.containsKey(c)){
                return false;
            }else{
                temp = temp.hm.get(c);
            }
            
        }
        
        return true;
    }
}
This post is licensed under CC BY 4.0 by the author.