Stripe 面试真题解析(六):Brace Expansion:实现类似 Bash 的花括号展开功能

9次阅读
没有评论

A comma-separated expression inside curly braces expands to a list of words.
If there is a prefix before the { or a suffix after the }, they also appear in each expansion.

Examples:

/2022/{jan,feb,mar}/report
→ /2022/jan/report
→ /2022/feb/report
→ /2022/mar/report

over{crowded,eager,ripe,tired}ness
→ overcrowdedness
→ overeagerness
→ overripeness
→ overtiredness

readme.txt{,.bak}
→ readme.txt
→ readme.txt.bak

Write a brace_expand function that takes a single pattern string and returns a list of expanded strings.
If the pattern is not expandable, return the original input as a one-element list.
Expand only when there are valid braces surrounding two or more tokens.

Examples:

pre{mat,ss}ure
→ premature
→ pressure

pre{mid}suf
→ pre{mid}suf   (not expanded)

Invalid braces should also return the original input unchanged:

hello-{world
→ hello-{world

Finally, handle multiple nested brace expressions:

/20{19,20}/{jan,feb,mar}/
→ /2019/jan/
→ /2019/feb/
→ /2019/mar/
→ /2020/jan/
→ /2020/feb/
→ /2020/mar/

pre{A,B,C}mid{X,Y}suf
→ preAmidXsuf
→ preAmidYsuf
→ preBmidXsuf
→ preBmidYsuf
→ preCmidXsuf
→ preCmidYsuf

{A,B}{1,2}{x,y}{P,Q}
→ A1xP, A1xQ, A1yP, A1yQ, A2xP, A2xQ, A2yP, A2yQ, B1xP, ...

The brace_expand function should recursively process all valid brace patterns and generate all possible expansions, similar to how Bash shell handles brace expressions.

这道题是一个非常经典的 字符串展开(brace expansion) 问题,灵感来源于 Bash Shell 的语法。
要求实现一个函数 brace_expand(pattern),能将带有 {} 花括号的模式字符串展开成所有可能的组合。

主要规则包括:

  • 花括号内用逗号分隔的内容会被展开;
  • 花括号外的前缀或后缀会自动拼接到每个展开结果中;
  • 如果括号无效(比如单独一个 {)或只有一个 token,不展开;
  • 支持多个括号的组合与嵌套(如 {A,B}{1,2}{x,y} → 16 种组合)。

考察点包括:

  • 递归字符串处理;
  • 组合生成与笛卡尔积逻辑;
  • 输入合法性判断与边界条件处理;
  • 对嵌套结构的解析和递归展开能力。

VOprep 团队长期陪同学员实战各类大厂 OA 与 VO,包括 Stripe、Google、Amazon、Citadel、SIG 等,提供实时语音助攻、远程陪练与面试节奏提醒,帮助大家在关键时刻不卡壳。
如果你也在准备 Stripe 或类似工程向公司,可以了解一下我们的定制助攻方案——从编程面到系统设计,全程护航上岸。

正文完
 0