Meta Interview Problem #1 · 文件路径解析(cd 命令模拟)

1次阅读
没有评论

Problem Statement (English original)
You are given a current working directory cwd (an absolute Unix-style path) and a cd(arg) string which can be either an absolute path (starts with /) or a relative path (may include segments . and ..).
Implement a function that returns the normalized absolute path after applying cd(arg) from cwd.

Rules:

  • Path separator is /.
  • . means“stay in the same directory”.
  • .. means“go to parent directory”(but never above root).
  • Collapse multiple slashes and remove trailing slash (except for root /).
  • The output must always be an absolute path.

Examples (from the prompt):

cwd cd(arg) output
/ foo /foo
/baz /bar /bar
/foo/bar ../../../../.. /
/x/y ./p/../q /x/q
/x/y /p/./q /p/q

给定当前目录 cwd(绝对路径)与一次 cd(arg 的参数(可以是绝对或相对路径,包含 ...),返回执行后 规范化的绝对路径
规则同上:/ 为分隔符,处理 ...,不越过根目录,折叠多余斜杠,移除末尾斜杠(根目录除外)。

简要总结 / Idea
处理:

  1. 若是绝对路径从空栈起,否则先把 cwd 分段入栈;
  2. 遍历 cd(arg) 的分段:忽略空与 .;遇到.. 弹栈;普通名入栈;
  3. / 连接栈,空栈返回 /。时间 O(L),空间 O(L)。

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

正文完
 0