-
Notifications
You must be signed in to change notification settings - Fork 0
/
1239.py
67 lines (49 loc) · 1.96 KB
/
1239.py
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 Solution:
def maxLength(self, arr: list[str]) -> int:
N = len(arr)
arr.sort(reverse=True, key=len)
max_len_all = len(set(''.join(arr)))
def explore(i: int, visited: set):
if i == N or len(visited) == max_len_all:
return len(visited)
new_visited = set(arr[i])
new_visited.update(visited)
max_len = 0
new_len = len(new_visited)
if new_len == len(visited) + len(arr[i]):
# may use this word...
max_len = max(max_len, explore(i+1, new_visited))
if max_len == max_len_all:
return max_len_all
# do not use current word...
max_len = max(max_len, explore(i+1, visited))
if max_len == max_len_all:
return max_len_all
return max_len
return explore(0, set())
class SolutionCleaner:
def maxLength(self, arr: list[str]) -> int:
N = len(arr)
arr.sort(reverse=True, key=len)
max_len_all = len(set(''.join(arr)))
def explore(i: int, visited: set):
if i == N or len(visited) == max_len_all:
return len(visited)
explore_sets = [visited]
new_visited = set(arr[i])
new_visited.update(visited)
if len(new_visited) == len(visited) + len(arr[i]):
# may use this word...
explore_sets.append(new_visited)
max_len = 0
for explore_set in explore_sets:
max_len = max(max_len, explore(i+1, explore_set))
if max_len == max_len_all:
return max_len_all
return max_len
return explore(0, set())
if __name__ == "__main__":
sol = Solution()
assert 4 == sol.maxLength(["un","iq","ue"])
assert 6 == sol.maxLength(["cha","r","act","ers"])
assert 26 == sol.maxLength(["abcdefghijklmnopqrstuvwxyz"])