1096. Brace Expansion II

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}}") = R("{ab,ac}{dfg,dfh,efg,efh}") = {"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: ["acd","ace","bcd","bce"]

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. 1 <= expression.length <= 50
  2. expression[i] consists of '{''}'','or lowercase English letters.
  3. The given expression represents a set of words based on the grammar given in the description.

思路:递归,

1. 第2个op就是set的union

2. 第3个op就是笛卡尔乘积

from itertools import product
class Solution(object):
    def braceExpansionII(self, expression):
        """
        :type expression: str
        :rtype: List[str]
        """
        if len(expression)==0: return ''
        st=[[]]
        cnt=start=0
        for i,v in enumerate(expression):
            if v=='{':
                if cnt==0: start=i+1
                cnt+=1
            elif v=='}':
                # 另外一个笛卡尔乘积的元素
                cnt-=1
                if cnt==0: st[-1].append(self.braceExpansionII(expression[start:i]))
            elif v==',':
                # 开辟另外一个数组存放另外一个新的笛卡尔乘积
                if cnt==0: st.append([])
            else:
                # 独立的字母,也看作笛卡尔乘积的一个元素,因为只有一个字母,所以笛卡尔乘积正好只选整个!
                if cnt==0: st[-1].append([v])
        
        res=set()
        for s in st:
            tmp=product(*s) # 计算一个笛卡尔乘积
            tmp=map(''.join, tmp) 
            res=res|set(tmp) # 不同笛卡尔乘积结果取union
        return sorted(res)
        
s=Solution()
print(s.braceExpansionII("{a,b}c{d,e}f"))
#print(s.braceExpansionII('{a,b}{c{d,e}}'))
#print(s.braceExpansionII('{{a,z},a{b,c},{ab,z}}'))

一开始想一层层的剥离括号,但是一直WA,需要考虑的case很多,如下,洋洋洒洒写了一大坨,但是还是fail了,还是抓住op计算的本质会好点

from collections import Counter
class Solution(object):
    def braceExpansionII(self, expression):
        """
        :type expression: str
        :rtype: List[str]
        """
        def merge(s1,s2):
            s=set()
            for ss1 in s1:
                for ss2 in s2:
                    s.add(ss1+ss2)
            return s
        
        def helper(s):
            if len(s)==0: return set()
            if '{' not in s: return set(s.split(','))
            
            cnt=0
            parts=[]
            ops=[]
            start=0
            for i in range(len(s)):
                if s[i]=='{': 
                    if cnt==0:
                        if s[start:i]!='':
                            if s[i-1]==',':
                                parts.append(s[start:i-1])
                                ops.append('add')
                            else:
                                parts.append(s[start:i])
                                ops.append('merge')
                            start=i
                    cnt+=1
                elif s[i]=='}':
                    cnt-=1
                    if cnt==0:
                        parts.append(s[start:i+1])
                        if i+1<len(s) and s[i+1]==',':
                            ops.append('add')
                            start=i+2
                        else:
                            ops.append('merge')
                            start=i+1
                elif i==len(s)-1:
                    if cnt==0:
                        if s[start:]!='':
                            parts.append(s[start:])
                            ops.append('merge')
                            start=i
                            
            print(parts)
            print(ops)
            tmps=[]
            for part in parts:
                if '{' in part: tmps.append(helper(part[1:len(part)-1]))
                else: tmps.append(helper(part))
            if len(tmps)==1: return tmps[0]
            else:
                res=set()
                cur=tmps[0]
                for i in range(len(tmps)-1):
                    if ops[i]=='add':
                        res=res|cur
                        cur=tmps[i+1]
                    else:
                        cur=merge(cur,tmps[i+1])
                res=res|cur
                return res
            
        return sorted(list(helper('{'+expression+'}')))

s=Solution()
print(s.braceExpansionII("{{a,l},ex,{ab,c}}"))
#print(s.braceExpansionII("{{a,b},b,c}"))
#print(s.braceExpansionII("{a,b}c{d,e}f"))
#print(s.braceExpansionII('{a,b}{c{d,e}}'))
#print(s.braceExpansionII('{{a,z},a{b,c},{ab,z}}'))

ps:这种题目写起来就是很tricky....

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值