LC.1096. Brace Expansion II

LC.1096. Brace Expansion II_第1张图片

class Solution(object):
    def braceExpansionII(self, expression):
        """
        {a,b}{c{d,e}} : ["acd","ace","bcd","bce"]
        {
     {a,z},a{b,c},{ab,z}} : ["a","ab","ac","z"]

        这道题的核心是递归匹配,每次去掉一层括号进行递归
        """
        char_stack = []

        # 将expression 分段去括号后的表达式存在split_array
        split_array = []
        # 这两个变量是为了匹配最外面括号里面的内容
        left_basket, right_basket = 0, 0
        if "{" in expression or "}" in expression:
            for char in expression:
                if char == "{":
                    left_basket +=1
                    char_stack.append(char)
                elif char == "}":
                    right_basket += 1
                    if left_basket == right_basket:
                        string = ""
                        while(left_basket != 0):
                            if char_stack[-1] == "{":
                                left_basket -=1
                            string += char_stack.pop()
                        # string 表示去掉以第一次出现的{为最外层括号内部的内容
                        string = string[::-1][1:]
                        left_basket, right_basket = 0, 0
                        split_array.append(self.braceExpansionII(string))
                    else:
                        char_stack.append(char)
                elif char == ",":
                    #表示这个逗号是括号之间的逗号
                    if left_basket == 0 and right_basket == 0 :
                        split_array.append(char)
                    else:
                        #表示这个逗号属于括号内部的逗号
                        char_stack.append(char)
                else:
                    if left_basket == 0 and right_basket == 0:
                        # 非括号内部的元素
                        split_array.append(char)
                    else:
                        char_stack.append(char)
        else:
            # 不存在括号,直接可以将expression转换
            split_array = expression.split(",")
            return split_array

        res = []
        stack = []
        for item in split_array:
            if len(stack) == 0 or item==",":
                stack.append(item)
            else:
                add = item[:]
                #表示当前要加入元素需要和栈顶的元素进行拼接
                while(len(stack) and stack[-1] != ","):
                    top_item = []
                    for ele1 in add:
                        for ele2 in stack[-1]:
                            top_item.append(ele2 + ele1)
                    add = top_item
                    stack.pop()
                stack.append(add)
        for item in stack:
            if item != ",":
                #注意这里用extend 而不是append,因为最终是生成一个一维list
                res.extend(item)
        return sorted(list(set(res)))

你可能感兴趣的:(LeetCode)