roovent

Trie

Jul 26th, 2018
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.98 KB | None | 0 0
  1. struct Trie {
  2.     class Node {
  3.         var children = [Character: Node]()
  4.         var isEOW = false // end of the word
  5.     }
  6.  
  7.     let root: Node
  8.  
  9.     init() {
  10.         root = Node()
  11.     }
  12.  
  13.     func insert(_ word: String) {
  14.         var node = root
  15.         for ch in word {
  16.             if node.children[ch] == nil {
  17.                 node.children[ch] = Node()
  18.             }
  19.             node = node.children[ch]!
  20.         }
  21.         node.isEOW = true
  22.         assert(search(word), "\(node)")
  23.     }
  24.  
  25.     func search(_ word: String) -> Bool {
  26.         return findLastNode(word)?.isEOW ?? false
  27.     }
  28.  
  29.     func startsWith(prefix: String) -> Bool {
  30.         return findLastNode(prefix) != nil
  31.     }
  32.  
  33.     private func findLastNode(_ word: String) -> Node? {
  34.         var node = root
  35.         for ch in word {
  36.             if let n = node.children[ch] {
  37.                 node = n
  38.             } else {
  39.                 return nil
  40.             }
  41.         }
  42.         return node
  43.     }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment