|
| 1 | +# Time: O(p*l * log(p*l)), p is the production of all number of options |
| 2 | +# , l is the length of a word |
| 3 | +# Space: O(p*l) |
| 4 | + |
| 5 | +import itertools |
| 6 | + |
| 7 | + |
| 8 | +class Solution(object): |
| 9 | + def braceExpansionII(self, expression): |
| 10 | + """ |
| 11 | + :type expression: str |
| 12 | + :rtype: List[str] |
| 13 | + """ |
| 14 | + def form_words(options): |
| 15 | + words = 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(expression, [0]) |
| 43 | + |
| 44 | + |
| 45 | +class Solution2(object): |
| 46 | + def braceExpansionII(self, expression): |
| 47 | + """ |
| 48 | + :type expression: str |
| 49 | + :rtype: List[str] |
| 50 | + """ |
| 51 | + def form_words(options): |
| 52 | + words = [] |
| 53 | + total = 1 |
| 54 | + for opt in options: |
| 55 | + total *= len(opt) |
| 56 | + for i in xrange(total): |
| 57 | + tmp = [] |
| 58 | + for opt in reversed(options): |
| 59 | + i, c = divmod(i, len(opt)) |
| 60 | + tmp.append(opt[c]) |
| 61 | + tmp.reverse() |
| 62 | + words.append("".join(tmp)) |
| 63 | + words.sort() |
| 64 | + return words |
| 65 | + |
| 66 | + def generate_option(expr, i): |
| 67 | + option_set = set() |
| 68 | + while i[0] != len(expr) and expr[i[0]] != "}": |
| 69 | + i[0] += 1 # { or , |
| 70 | + for option in generate_words(expr, i): |
| 71 | + option_set.add(option) |
| 72 | + i[0] += 1 # } |
| 73 | + option = list(option_set) |
| 74 | + option.sort() |
| 75 | + return option |
| 76 | + |
| 77 | + def generate_words(expr, i): |
| 78 | + options = [] |
| 79 | + while i[0] != len(expr) and expr[i[0]] not in ",}": |
| 80 | + tmp = [] |
| 81 | + if expr[i[0]] not in "{,}": |
| 82 | + tmp.append(expr[i[0]]) |
| 83 | + i[0] += 1 # a-z |
| 84 | + elif expr[i[0]] == "{": |
| 85 | + tmp = generate_option(expr, i) |
| 86 | + options.append(tmp) |
| 87 | + return form_words(options) |
| 88 | + |
| 89 | + return generate_words(expression, [0]) |
0 commit comments