Under a grammar given below, strings can represent a set of lowercase words.  Let's use R(expr) to denote the set of words the expression represents.
Grammar can best be understood through simple examples:

Single letters represent a singleton set containing that word.
        
R("a") = {"a"}
R("w") = {"w"}


When we take a comma delimited list of 2 or more expressions, we take the union of possibilities.
        
R("{a,b,c}") = {"a","b","c"}
R("{{a,b},{b,c}}") = {"a","b","c"} (notice the final set only contains each word at most once)


When we concatenate two expressions, we take the set of possible concatenations between two words where the first word comes from the first expression and the second word comes from the second expression.
        
R("{a,b}{c,d}") = {"ac","ad","bc","bd"}
R("a{b,c}{d,e}f{g,h}") = {"abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"}



Formally, the 3 rules for our grammar:

For every lowercase letter x, we have R(x) = {x}
For expressions e_1, e_2, ... , e_k with k >= 2, we have R({e_1,e_2,...}) = R(e_1) ∪ R(e_2) ∪ ...
For expressions e_1 and e_2, we have R(e_1 + e_2) = {a + b for (a, b) in R(e_1) × R(e_2)}, where + denotes concatenation, and × denotes the cartesian product.

Given an expression representing a set of words under the given grammar, return the sorted list of words that the expression represents.
 

Example 1:
Input: "{a,b}{c,{d,e}}"
Output: ["ac","ad","ae","bc","bd","be"]


Example 2:
Input: "{{a,z},a{b,c},{ab,z}}"
Output: ["a","ab","ac","z"]
Explanation: Each distinct word is written only once in the final answer.

 
Constraints:

1 <= expression.length <= 60
expression[i] consists of '{', '}', ','or lowercase English letters.
The given expression represents a set of words based on the grammar given in the description.

Difficulty: MEDIUM_HARD
Tags: String algorithms

Data structures

Graph traversal

Complete search
Skill types: Data structures

Complete search

Starter code:
class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        

Solutions:
class Solution:

	def braceExpansionII(self, expression: str) -> List[str]:
		(stack, res, cur) = ([], [], [''])
		for v in expression:
			if v.isalpha():
				cur = [c + v for c in cur]
			elif v == ',':
				res += cur
				cur = ['']
			elif v == '{':
				stack.append(res)
				stack.append(cur)
				(res, cur) = ([], [''])
			elif v == '}':
				preCur = stack.pop()
				preRes = stack.pop()
				cur = [p + c for p in preCur for c in res + cur]
				res = preRes
		return sorted(set(res + cur))


class Solution:

	def braceExpansionII(self, expression: str) -> List[str]:
		stack = []
		prev = set()
		curr = set()
		for s in expression:
			if s == '{':
				stack.append(prev)
				stack.append(curr)
				curr = set()
				prev = set()
			elif s == '}':
				k = stack.pop()
				p = set()
				for i in k or ['']:
					for j in prev | curr:
						p.add(i + j)
				prev = stack.pop()
				curr = p
			elif s == ',':
				prev |= curr
				curr = set()
			else:
				p = set()
				for c in curr or ['']:
					p.add(c + s)
				curr = p
		return list(sorted(curr))


class Solution:

	def braceExpansionII(self, expression: str) -> List[str]:
		(stack, res, cur) = ([], [], [''])
		for (i, v) in enumerate(expression):
			print(v)
			print(stack)
			print(res, cur)
			if v.isalpha():
				cur = [c + v for c in cur]
			elif v == '{':
				stack.append(res)
				stack.append(cur)
				(res, cur) = ([], [''])
			elif v == '}':
				precur = stack.pop()
				preres = stack.pop()
				cur = [p + c for p in precur for c in res + cur]
				res = preres
			elif v == ',':
				res += cur
				cur = ['']
		return sorted(set(res + cur))


class Solution:

	def braceExpansionII(self, expression: str) -> List[str]:
		stack = []
		for letter in expression:
			if letter.isalpha():
				stack.append(set(letter))
			elif letter == '{':
				stack.append('{')
			elif letter == ',':
				stack.append(',')
			elif letter == '}':
				while stack[-2] == ',':
					set2 = stack.pop()
					stack.pop()
					stack[-1].update(set2)
				tail = stack.pop()
				stack[-1] = tail
			while len(stack) > 1 and isinstance(stack[-1], set) and isinstance(stack[-2], set):
				set2 = stack.pop()
				set1 = stack.pop()
				stack.append(set((w1 + w2 for w1 in set1 for w2 in set2)))
		return list(sorted(stack[-1]))


class Solution:

	def braceExpansionII(self, expression: str) -> List[str]:
		groups = [[]]
		level = 0
		for (i, c) in enumerate(expression):
			if c == '{':
				if level == 0:
					start = i + 1
				level += 1
			elif c == '}':
				level -= 1
				if level == 0:
					groups[-1].append(self.braceExpansionII(expression[start:i]))
			elif c == ',' and level == 0:
				groups.append([])
			elif level == 0:
				groups[-1].append([c])
		word_set = set()
		for group in groups:
			word_set |= set(map(''.join, itertools.product(*group)))
		return sorted(word_set)


import itertools
from abc import ABC, abstractmethod

class Syntax(ABC):

	def __init__(self, next=None):
		self.next = next

	@abstractmethod
	def get_values(self):
		return []

	def get_strings(self):
		if self.next is None:
			return self.get_values()
		return (a + b for a in self.get_values() for b in self.next.get_strings())

class Letter(Syntax):

	def __init__(self, letter, next=None):
		super().__init__(next)
		self.letter = letter

	def get_values(self):
		return [self.letter]

class Union(Syntax):

	def __init__(self, elts, next=None):
		super().__init__(next)
		self.elts = elts

	def get_values(self):
		return itertools.chain(*[elt.get_strings() for elt in self.elts])

class Solution:

	def find_close_brace(self, expression, offset):
		level = 1
		while level:
			offset += 1
			if expression[offset] == '{':
				level += 1
			elif expression[offset] == '}':
				level -= 1
		return offset

	def split_union_commas(self, expression):
		left = 0
		curr = 0
		expressions = []
		while left < len(expression):
			if expression[curr] == '{':
				curr = self.find_close_brace(expression, curr) + 1
			elif expression[curr] == ',':
				expressions.append(expression[left:curr])
				curr += 1
				left = curr
			else:
				curr += 1
			if curr == len(expression):
				expressions.append(expression[left:curr])
				break
		return expressions

	def parse(self, expression, offset):
		if offset == len(expression):
			return None
		if expression[offset] != '{':
			try:
				word_end = expression.index('{', offset)
			except ValueError:
				word_end = len(expression)
			return Letter(expression[offset:word_end], self.parse(expression, word_end))
		close_idx = self.find_close_brace(expression, offset)
		return Union(self.parse_union(expression[offset + 1:close_idx]), self.parse(expression, close_idx + 1))

	def parse_union(self, expression):
		elts = self.split_union_commas(expression)
		return [self.parse(elt, 0) for elt in elts]

	def braceExpansionII(self, expression: str) -> List[str]:
		head = self.parse(expression, 0)
		if head is None:
			return []
		return sorted(list(set(head.get_strings())))