leetcde1096. 花括号展开 II

题目:
https://leetcode-cn.com/problems/brace-expansion-ii/

//这道题还是得使用递归的思想,每个花括号执行一次

int step = 0;//防止出现重复判断
int n = 0;

public List braceExpansionII(String expression) {
    n = expression.length();
    char[] chars = expression.toCharArray();
    List list = new ArrayList<>(brace(chars, 0));
    list.sort((o1, o2) -> {
        return o1.compareTo(o2);
    });
    return list;
}

private Set brace(char[] chars, int start) {
    Set ans = new HashSet<>();
    Set lAns = new HashSet<>();
    String lStr = "";
    for (int i = start; i < n; i++) {
        if (chars[i] == '{') {
            if (lStr.length() > 0) {
                lAns = mix(lAns, lStr);
                lStr = "";
            }
            Set ll = brace(chars, i + 1);
            if (lAns.size() == 0) {
                lAns = ll;
            } else {
                lAns = mix(lAns, ll);
            }
            i = step;
        } else if (chars[i] == '}') {
            step = i;
            if (lAns.size() == 0) {
                if (lStr.length() > 0) {
                    ans.add(lStr);
                }
            } else {
                if (lStr.length() > 0) {
                    lAns = mix(lAns, lStr);
                }
                ans.addAll(lAns);
            }
            ans.addAll(lAns);
            return ans;
        } else if (chars[i] == ',') {
            if (lStr.length() > 0) {
                lAns = mix(lAns, lStr);
                lStr = "";
            }
            ans.addAll(lAns);
            lAns = new HashSet<>();
        } else if (chars[i] == ' ') {
            continue;
        } else {
            lStr += chars[i];
        }

    }
    step = n;
    if (lAns.size() == 0) {
        if (lStr.length() > 0) {
            ans.add(lStr);
        }
    } else {
        if (lStr.length() > 0) {
            lAns = mix(lAns, lStr);
        }
        ans.addAll(lAns);
    }
    return ans;
}

private Set mix(Set ans, Set lAns) {
    if (ans.size() == 0) {
        return lAns;
    }
    Set set = new HashSet<>();
    for (String an : ans) {
        for (String lAn : lAns) {
            set.add(an + lAn);
        }
    }
    return set;
}

private Set mix(Set ans, String str) {

    if (ans.size() == 0) {
        Set set = new HashSet<>();
        set.add(str);
        return set;
    }
    Set set = new HashSet<>();
    for (String an : ans) {
        set.add(an + str);
    }
    return set;
}

你可能感兴趣的:(leetcode,算法,笔记)