LeetCode //C - 1096. Brace Expansion II

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"

Explanation: arr becomes 15,15,15,9,10,10,10

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
  • expressioni consists of '{', '}', ','or lowercase English letters.
  • The given expression represents a set of words based on the grammar given in the description.

From: LeetCode

Link: 1096. Brace Expansion II


Solution:

Ideas:

Recursively parse the expression, using union for commas and Cartesian product for concatenation, while accumulating results in sets to remove duplicates and sorting at the end.

Code:
c 复制代码
typedef struct {
    char** a;
    int size;
    int cap;
} Set;

static char* dupStr(const char* s) {
    char* p = (char*)malloc(strlen(s) + 1);
    strcpy(p, s);
    return p;
}

static void initSet(Set* s) {
    s->size = 0;
    s->cap = 16;
    s->a = (char**)malloc(sizeof(char*) * s->cap);
}

static void freeSet(Set* s) {
    for (int i = 0; i < s->size; i++) free(s->a[i]);
    free(s->a);
}

static void addStr(Set* s, const char* str) {
    for (int i = 0; i < s->size; i++) {
        if (strcmp(s->a[i], str) == 0) return;
    }

    if (s->size == s->cap) {
        s->cap *= 2;
        s->a = (char**)realloc(s->a, sizeof(char*) * s->cap);
    }

    s->a[s->size++] = dupStr(str);
}

static Set unionSet(Set x, Set y) {
    Set res;
    initSet(&res);

    for (int i = 0; i < x.size; i++) addStr(&res, x.a[i]);
    for (int i = 0; i < y.size; i++) addStr(&res, y.a[i]);

    freeSet(&x);
    freeSet(&y);
    return res;
}

static Set productSet(Set x, Set y) {
    Set res;
    initSet(&res);

    for (int i = 0; i < x.size; i++) {
        for (int j = 0; j < y.size; j++) {
            int len = strlen(x.a[i]) + strlen(y.a[j]);
            char* tmp = (char*)malloc(len + 1);

            strcpy(tmp, x.a[i]);
            strcat(tmp, y.a[j]);

            addStr(&res, tmp);
            free(tmp);
        }
    }

    freeSet(&x);
    freeSet(&y);
    return res;
}

static Set parse(char* expression, int* idx) {
    Set result;
    initSet(&result);   // empty union result

    Set current;
    initSet(&current);
    addStr(&current, "");   // identity for concatenation

    while (expression[*idx] && expression[*idx] != '}') {
        if (expression[*idx] == ',') {
            result = unionSet(result, current);

            initSet(&current);
            addStr(&current, "");

            (*idx)++;
        } else {
            Set next;
            initSet(&next);

            if (expression[*idx] == '{') {
                (*idx)++;
                next = parse(expression, idx);
                (*idx)++;   // skip '}'
            } else {
                char temp[2] = {expression[*idx], '\0'};
                addStr(&next, temp);
                (*idx)++;
            }

            current = productSet(current, next);
        }
    }

    result = unionSet(result, current);
    return result;
}

static int cmpStr(const void* a, const void* b) {
    return strcmp(*(char**)a, *(char**)b);
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
char** braceExpansionII(char* expression, int* returnSize) {
    int idx = 0;
    Set ans = parse(expression, &idx);

    qsort(ans.a, ans.size, sizeof(char*), cmpStr);

    *returnSize = ans.size;
    return ans.a;
}
相关推荐
Eloudy2 分钟前
预词力:LLM 的唯一形式化能力
人工智能·算法·agent
嵌入式阿蔡8 分钟前
CAN总线入门:从协议帧到STM32实战
c语言·stm32·单片机·嵌入式硬件·嵌入式实时数据库
依然鸣19 分钟前
PTA团体程序设计天梯赛L1真题讲解L1-085-088
数据结构·c++·经验分享·算法·深度优先·pat考试
听取WA声一片(无恶意)1 小时前
CSP-J/S 初赛图论完全讲义
算法·csp-s初赛·csp-j初赛
Brilliantwxx1 小时前
【算法从零到千】【51-54】逆序对(分治+递归算法)
数据结构·算法·排序算法
LONGZETECH1 小时前
无人机组装调试实训高损耗痛点分析与虚拟仿真教学落地方案
c语言·开发语言·架构·无人机
小星星闪亮登场1 小时前
2026河南萌新联赛第四场--南阳理工学院
数据结构·算法·贪心算法·动态规划·哈希算法·广度优先
土司大王1 小时前
LeetCode hot100——两数之和
数据结构·算法·leetcode
luj_17682 小时前
大航海时代:沉浸式财商实战沙盒
c语言·开发语言·网络·经验分享·算法
Navigator_Z2 小时前
LeetCode //C - 1200. Minimum Absolute Difference
c语言·算法·leetcode