forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.swift
67 lines (58 loc) · 1.59 KB
/
Solution.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
class TrieNode {
var idx: Int
var children: [TrieNode?]
init() {
self.idx = -1
self.children = Array(repeating: nil, count: 26)
}
}
class Trie {
private let root: TrieNode
init() {
self.root = TrieNode()
}
func insert(_ word: String, _ index: Int) {
var node = root
for ch in word {
let i = Int(ch.asciiValue! - Character("a").asciiValue!)
if node.children[i] == nil {
node.children[i] = TrieNode()
}
node = node.children[i]!
}
node.idx = index
}
func search(_ word: String) -> [Int] {
var node = root
var results = [Int]()
for ch in word {
let i = Int(ch.asciiValue! - Character("a").asciiValue!)
if node.children[i] == nil {
break
}
node = node.children[i]!
if node.idx != -1 {
results.append(node.idx)
}
}
return results
}
}
class Solution {
func multiSearch(_ big: String, _ smalls: [String]) -> [[Int]] {
let trie = Trie()
for (index, small) in smalls.enumerated() {
trie.insert(small, index)
}
var results = Array(repeating: [Int](), count: smalls.count)
let bigChars = Array(big)
for i in 0..<bigChars.count {
let substring = String(bigChars[i...])
let indices = trie.search(substring)
for index in indices {
results[index].append(i)
}
}
return results
}
}