forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
brace-expansion-ii.py
89 lines (78 loc) · 2.74 KB
/
brace-expansion-ii.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# Time: O(p*l * log(p*l)), p is the production of all number of options
# , l is the length of a word
# Space: O(p*l)
import itertools
class Solution(object):
def braceExpansionII(self, expression):
"""
:type expression: str
:rtype: List[str]
"""
def form_words(options):
words = map("".join, itertools.product(*options))
words.sort()
return words
def generate_option(expr, i):
option_set = set()
while i[0] != len(expr) and expr[i[0]] != "}":
i[0] += 1 # { or ,
for option in generate_words(expr, i):
option_set.add(option)
i[0] += 1 # }
option = list(option_set)
option.sort()
return option
def generate_words(expr, i):
options = []
while i[0] != len(expr) and expr[i[0]] not in ",}":
tmp = []
if expr[i[0]] not in "{,}":
tmp.append(expr[i[0]])
i[0] += 1 # a-z
elif expr[i[0]] == "{":
tmp = generate_option(expr, i)
options.append(tmp)
return form_words(options)
return generate_words(expression, [0])
class Solution2(object):
def braceExpansionII(self, expression):
"""
:type expression: str
:rtype: List[str]
"""
def form_words(options):
words = []
total = 1
for opt in options:
total *= len(opt)
for i in xrange(total):
tmp = []
for opt in reversed(options):
i, c = divmod(i, len(opt))
tmp.append(opt[c])
tmp.reverse()
words.append("".join(tmp))
words.sort()
return words
def generate_option(expr, i):
option_set = set()
while i[0] != len(expr) and expr[i[0]] != "}":
i[0] += 1 # { or ,
for option in generate_words(expr, i):
option_set.add(option)
i[0] += 1 # }
option = list(option_set)
option.sort()
return option
def generate_words(expr, i):
options = []
while i[0] != len(expr) and expr[i[0]] not in ",}":
tmp = []
if expr[i[0]] not in "{,}":
tmp.append(expr[i[0]])
i[0] += 1 # a-z
elif expr[i[0]] == "{":
tmp = generate_option(expr, i)
options.append(tmp)
return form_words(options)
return generate_words(expression, [0])