Original Summary

佬友们中秋节快乐!! 力扣 LeetCode 1096. 花括号展开 II - 力扣(LeetCode) 1096. 花括号展开 II - 如果你熟悉 Shell 编程,那么一定了解过花括号展开,它可以用来生成任意字符串。 花括号展开的表达式可以看作一个由 花括号、逗号 和 小写英文字母 组成的字符串,定义下面几条语法规则: 如果只给出单一的元素 x,那么表达式表示的字符串就只有 "x"。R(x) = {x} 例如,表达式 "a" 表示字符串 "a"。 而表达式 "w" 就表示字符串 "w"。 ... 思路 跟四则运算思路差不多,递归,根据优先级和符号依次运算。 花括号内,从左往右遍历。缓存 now 存还没结束的内容。 如果遇到 { ,找到对应的 } ,然后递归它中间的内容,然后与当前缓存值连接。 如果遇到 , ,把缓存加到 ans ,重置当前缓存。 否则将缓存中的值依次与当前字符连接。 遍历结束后,如果缓存中还有值,加入到 ans 。 代码 class Solution { private char[] chars; public List<String> braceExpansionII(String expression) { chars = expression.toCharArray(); Set<String> ans = dfs(0, chars.length - 1); return ans.stream().sorted().toList(); } private HashSet<String> dfs(int left, int right) { int idx = left; HashSet<String> ans = new HashSet<>(); HashSet<String> now = new HashSet<>(); now.add(""); while (idx <= right) { if (chars[idx] == '{') { int l = ++idx; int deep = 1; while (idx <= right){ if (chars[idx] == '}') { if (--deep == 0) { idx++; break; } } else if (chars[idx] == '{') { deep++; } idx++; } HashSet<String> link = dfs(l, idx - 2); HashSet<String> next = new HashSet<>(); for (String s : now) { for (String s1 : link) { next.add(s + s1); } } now = next; } else if (chars[idx] == ',') { ans.addAll(now); now.clear(); now.add(""); idx++; } else { HashSet<String> next = new HashSet<>(); for (String s : now) { next.add(s + chars[idx]); } now = next; idx++; } } if (!now.isEmpty()) { ans.addAll(now); } return ans; } } 1 个帖子 - 1 位参与者 阅读完整话题


  • 情报分类:技术学习与提效
  • 分类依据:内容涉及技术、AI、软件工具或工程实践
  • 信息来源:服务器 / LINUX DO - 最新话题
  • 发布时间:2026/9/25 08:52:41