Algorithm


Problem Name: 1096. Brace Expansion II

Under the grammar given below, strings can represent a set of lowercase words. Let R(expr) denote the set of words the expression represents.

The 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 two 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 three rules for our grammar:

  • For every lowercase letter x, we have R(x) = {x}.
  • For expressions e1, e2, ... , ek with k >= 2, we have R({e1, e2, ...}) = R(e1) ∪ R(e2) ∪ ...
  • For expressions e1 and e2, we have R(e1 + e2) = {a + b for (a, b) in R(e1) × R(e2)}, 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: expression = "{a,b}{c,{d,e}}"
Output: ["ac","ad","ae","bc","bd","be"]

Example 2:

Input: expression = "{{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.

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const braceExpansionII = function (expression) {
  expression = expression.replace(/([a-z]){1}/g, '{$1}')
  const stk = new Array()
  for (let char of expression) {
    if (char !== '}') {
      stk.push(char)
    } else {
      let str = '',
        prev = '',
        temp = ''
      while (stk[stk.length - 1] != '{') {
        prev = temp
        temp = stk.pop()
        if (temp == ',' || prev == ',' || str == '') str = temp + str
        else {
          str = str
            .split(',')
            .map((item) => {
              let ar = new Array()
              for (let ch of temp.split(',')) ar.push(ch + item)
              return ar.join(',')
            })
            .join(',')
        }
      }
      stk.pop()
      while (
        stk.length > 0 &&
        stk[stk.length - 1] != ',' &&
        stk[stk.length - 1] != '{'
      ) {
        temp = stk.pop()
        str = str
          .split(',')
          .map((item) => {
            let ar = new Array()
            for (let ch of temp.split(',')) ar.push(ch + item)
            return ar.join(',')
          })
          .join(',')
      }

      if (str.length > 0) stk.push(str)
    }
  }

  return [...new Set(stk[0].split(','))].sort()
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
expression = "{a,b}{c,{d,e}}"

Output

x
+
cmd
["ac","ad","ae","bc","bd","be"]

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def braceExpansionII(self, expression: str) -> List[str]:
        stack,res,cur=[],[],[]
        for i in range(len(expression)):
            v=expression[i]
            if v.isalpha():
                cur=[c+v for c in cur or ['']]
            elif v=='{':
                stack.append(res)
                stack.append(cur)
                res,cur=[],[]
            elif v=='}':
                pre=stack.pop()
                preRes=stack.pop()
                cur=[p+c for c in res+cur for p in pre or ['']]
                res=preRes
            elif v==',':
                res+=cur
                cur=[]
        return sorted(set(res+cur))
        
Copy The Code & Try With Live Editor

Input

x
+
cmd
expression = "{a,b}{c,{d,e}}"

Output

x
+
cmd
["ac","ad","ae","bc","bd","be"]

#3 Code Example with C# Programming

Code - C# Programming


using System.Collections.Generic;
using System.Linq;

namespace LeetCode
{
    public class _1096_BraceExpansionII
    {
        public IList < string> BraceExpansionII(string expression)
        {
            var stack = new Stack();
            var product = new List() { "" };

            foreach (var ch in expression)
            {
                if (ch >= 'a' && ch  < = 'z')
                {
                    for (int i = 0; i < product.Count; i++)
                        product[i] += ch;
                }
                else if (ch == '{')
                {
                    stack.Push(union);
                    stack.Push(product);
                    union = new List < string>();
                    product = new List() { "" };
                }
                else if (ch == '}')
                {
                    var pre_product = stack.Pop();
                    var pre_union = stack.Pop();

                    union.AddRange(product);
                    product = new List < string>();
                    foreach (var str1 in pre_product)
                        foreach (var str2 in union)
                            product.Add(str1 + str2);
                    union = pre_union;
                }
                else
                {
                    union.AddRange(product);
                    product = new List < string>() { "" };
                }
            }

            union.AddRange(product);
            return union.Distinct().OrderBy(s => s).ToList();
        }
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
expression = "{{a,z},a{b,c},{ab,z}}"

Output

x
+
cmd
["a","ab","ac","z"]
Advertisements

Demonstration


Previous
#1095 Leetcode Find in Mountain Array Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#1103 Leetcode Distribute Candies to People Solution in C, C++, Java, JavaScript, Python, C# Leetcode