-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.go
73 lines (71 loc) · 1.27 KB
/
Solution.go
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
type Trie struct {
children [26]*Trie
isEnd bool
}
func newTrie() *Trie {
return &Trie{}
}
func (this *Trie) insert(word string) {
node := this
for _, c := range word {
c -= 'a'
if node.children[c] == nil {
node.children[c] = newTrie()
}
node = node.children[c]
}
node.isEnd = true
}
func maxRectangle(words []string) (ans []string) {
trie := newTrie()
d := map[int][]string{}
t := []string{}
var maxL, maxS int
for _, w := range words {
maxL = max(maxL, len(w))
d[len(w)] = append(d[len(w)], w)
trie.insert(w)
}
check := func(mat []string) int {
m, n := len(mat), len(mat[0])
ans := 1
for j := 0; j < n; j++ {
node := trie
for i := 0; i < m; i++ {
idx := mat[i][j] - 'a'
if node.children[idx] == nil {
return 0
}
node = node.children[idx]
}
if !node.isEnd {
ans = 2
}
}
return ans
}
var dfs func([]string)
dfs = func(ws []string) {
if len(ws[0])*maxL <= maxS || len(t) >= maxL {
return
}
for _, w := range ws {
t = append(t, w)
st := check(t)
if st == 0 {
t = t[:len(t)-1]
continue
}
if st == 1 && maxS < len(t)*len(t[0]) {
maxS = len(t) * len(t[0])
ans = append([]string{}, t...)
}
dfs(ws)
t = t[:len(t)-1]
}
}
for _, ws := range d {
dfs(ws)
}
return
}