Skip to content

Commit 5ee0b36

Browse files
authored
Update brace-expansion.py
1 parent e705c58 commit 5ee0b36

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Python/brace-expansion.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,47 @@
22
# , l is the length of a word
33
# Space: O(p*l)
44

5+
import itertools
6+
7+
58
class Solution(object):
9+
def expand(self, S): # nested is fine
10+
"""
11+
:type S: str
12+
:rtype: List[str]
13+
"""
14+
def form_words(options):
15+
words = list(map("".join, itertools.product(*options)))
16+
words.sort()
17+
return words
18+
19+
def generate_option(expr, i):
20+
option_set = set()
21+
while i[0] != len(expr) and expr[i[0]] != "}":
22+
i[0] += 1 # { or ,
23+
for option in generate_words(expr, i):
24+
option_set.add(option)
25+
i[0] += 1 # }
26+
option = list(option_set)
27+
option.sort()
28+
return option
29+
30+
def generate_words(expr, i):
31+
options = []
32+
while i[0] != len(expr) and expr[i[0]] not in ",}":
33+
tmp = []
34+
if expr[i[0]] not in "{,}":
35+
tmp.append(expr[i[0]])
36+
i[0] += 1 # a-z
37+
elif expr[i[0]] == "{":
38+
tmp = generate_option(expr, i)
39+
options.append(tmp)
40+
return form_words(options)
41+
42+
return generate_words(S, [0])
43+
44+
45+
class Solution2(object):
646
def expand(self, S): # nested is fine
747
"""
848
:type S: str

0 commit comments

Comments
 (0)