-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.swift
78 lines (72 loc) · 2.08 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
68
69
70
71
72
73
74
75
76
77
78
class Trie {
var children = [Trie?](repeating: nil, count: 26)
var isEnd = false
func insert(_ word: String) {
var node = self
for c in word {
let index = Int(c.asciiValue! - Character("a").asciiValue!)
if node.children[index] == nil {
node.children[index] = Trie()
}
node = node.children[index]!
}
node.isEnd = true
}
}
class Solution {
private var maxL = 0
private var maxS = 0
private var ans: [String] = []
private var trie = Trie()
private var t = [String]()
func maxRectangle(_ words: [String]) -> [String] {
var d = [Int: [String]]()
for word in words {
maxL = max(maxL, word.count)
trie.insert(word)
d[word.count, default: []].append(word)
}
for ws in d.values {
t.removeAll()
dfs(ws)
}
return ans
}
private func dfs(_ ws: [String]) {
guard let first = ws.first, first.count * maxL > maxS, t.count < maxL else { return }
for w in ws {
t.append(w)
let st = check(t)
switch st {
case 0:
t.removeLast()
case 1:
if maxS < t.count * t[0].count {
maxS = t.count * t[0].count
ans = t
}
dfs(ws)
t.removeLast()
default:
dfs(ws)
t.removeLast()
}
}
}
private func check(_ mat: [String]) -> Int {
let m = mat.count, n = mat[0].count
var result = 1
for j in 0..<n {
var node = trie
for i in 0..<m {
let index = Int(mat[i][mat[i].index(mat[i].startIndex, offsetBy: j)].asciiValue! - Character("a").asciiValue!)
guard let nextNode = node.children[index] else { return 0 }
node = nextNode
}
if !node.isEnd {
result = 2
}
}
return result
}
}