-
Notifications
You must be signed in to change notification settings - Fork 0
/
14Trie.swift
76 lines (66 loc) · 2.02 KB
/
14Trie.swift
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
//
// ViewController.swift
// StockPrices
//
// Created by thailinh on 5/15/20.
// Copyright © 2020 thailinh. All rights reserved.
//
import UIKit
struct TrieNode{
var isword = false
var next : [TrieNode?] = Array(repeating: nil, count: 26)
}
// TRIE
class Trie {
private var root : TrieNode!
func find(s : String) -> TrieNode?{
var rootTemp = root
for char in s{
let index : Int = Int(char.unicodeScalars.first!.value - 97)
if rootTemp!.next[index] == nil{
return nil
}
rootTemp = rootTemp!.next[index]
}
return rootTemp
}
/** Initialize your data structure here. */
init() {
root = TrieNode()
}
/** Inserts a word into the trie. */
func insert(_ word: String) {
insertRecursive(node: &root!, index: 0, word: word)
}
func insertRecursive(node : inout TrieNode, index : Int, word : String){
guard index < word.count else{
node.isword = true
return
}
let char = getCharacterAtIndex(index: index, string: word)
let idx : Int = Int(char.unicodeScalars.first!.value - 97)
if (node.next[idx] == nil){
node.next[idx] = TrieNode()
}
insertRecursive(node: &node.next[idx]!, index: index + 1, word: word)
}
func getCharacterAtIndex(index : Int, string : String) -> Character{
let indexStr = string.index(string.startIndex, offsetBy: index)
return string[indexStr]
}
/** Returns if the word is in the trie. */
func search(_ word: String) -> Bool {
let rootTemp = find(s: word)
if rootTemp != nil && rootTemp?.isword == true{
return true
}
return false
}
/** Returns if there is any word in the trie that starts with the given prefix. */
func startsWith(_ prefix: String) -> Bool {
if find(s: prefix) == nil{
return false
}
return true
}
}