Meta VO 面试真题解析:Unix cd 命令路径模拟

18次阅读
没有评论

Implement a mock of the Unix cd (change directory) command.

The code does not have to change actual directories; it only needs to return the new path after cd is executed.

The function takes two arguments: the current working directory and the directory to change to, and returns the output directory as if the cd command were executed. There is a filesystem underneath, and all paths are valid.

Question statement

Example table of inputs and outputs:

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

这题要求实现一个 Unix 风格的 cd 路径模拟器:给定当前目录 cwd 和待切换路径 arg,返回执行 cd 后的目标路径,但不需要真的访问文件系统。核心做法是把路径按“/”分段后用栈处理:遇到普通目录就入栈,遇到“..”就回退一层,遇到“.”或空段则忽略。若 arg 是绝对路径则从根目录开始,若是相对路径则从 cwd 出发。最后把栈中的目录重新拼成规范化路径即可。

正文完
 0