Advertisement
carmenne

Untitled

Mar 28th, 2020
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. class Trie {
  2.  
  3.     Node root;
  4.     /** Initialize your data structure here. */
  5.     public Trie() {
  6.         root = new Node();
  7.     }
  8.    
  9.     /** Inserts a word into the trie. */
  10.     public void insert(String word) {
  11.        
  12.         Node current = root;
  13.        
  14.         for (char c: word.toCharArray()) {
  15.             if (current.children[c - 'a'] != null) {
  16.                 current.count++;
  17.             } else {
  18.                 current.children[c - 'a'] = new Node();
  19.             }
  20.             current = current.children[c - 'a'];
  21.         }
  22.         current.isFinal = true;
  23.        
  24.        
  25.     }
  26.    
  27.     /** Returns if the word is in the trie. */
  28.     public boolean search(String word) {
  29.        
  30.         Node current = root;
  31.         for (char c: word.toCharArray()) {
  32.             if (current.children[c - 'a'] == null) {
  33.                 return false;
  34.             }
  35.             current = current.children[c - 'a'];
  36.         }
  37.         return current.isFinal;
  38.        
  39.     }
  40.    
  41.     /** Returns if there is any word in the trie that starts with the given prefix. */
  42.     public boolean startsWith(String prefix) {
  43.         Node current = root;
  44.         for (char c: prefix.toCharArray()) {
  45.             if (current.children[c - 'a'] == null) {
  46.                 return false;
  47.             }
  48.             current = current.children[c - 'a'];
  49.         }
  50.         return true;
  51.     }
  52.    
  53.     static class Node {
  54.         Node[] children;
  55.         boolean isFinal;
  56.         int count;
  57.        
  58.         public Node() {
  59.             children = new Node[26];
  60.         }
  61.     }
  62. }
  63.  
  64. /**
  65.  * Your Trie object will be instantiated and called as such:
  66.  * Trie obj = new Trie();
  67.  * obj.insert(word);
  68.  * boolean param_2 = obj.search(word);
  69.  * boolean param_3 = obj.startsWith(prefix);
  70.  */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement