← 返回 openai 的题目列表Implement Unix-like `cd` Command (with Symlink Follow-up)
类型:online_judge
Problem: Implement a Unix-like cd Command (with Symlink Follow-up)
Implement a simplified cd (change directory). Given the current working directory cwd and a target path, return the resulting directory after applying cd.
You must support at least the following path semantics:
Absolute paths: start with /, e.g. /a/b.
Relative paths: e.g. a/b, interpreted relative to cwd.
Special segments:
. means current directory (ignore).
.. means parent directory (staying at / if already at root).
Redundant slashes should be treated as a single separator (e.g. /a//b/ equals /a/b).
Output: a normalized absolute path string (starts with / and does not end with / unless it is the root).
Follow-up: Add Symbolic Links (symlinks)
The system has a symlink mapping links where links[src] = dst. While resolving a path, whenever the resolution reaches src, it should jump to dst (dst may be absolute or relative).
Describe or implement how to handle:
symlinks appearing in the middle of a path
multi-hop symlink chains
symlink cycles (e.g., /a -> /b, /b -> /a)
Constraints
Total path length L: 1 <= L <= 1e5
Number of symlinks M: 0 <= M <= 1e5
Example Tests
cwd=/a/b, path=../c → /a/c
cwd=/, path=../../x → /x
cwd=/a, path=/a//b/./c → /a/b/c
(with symlink) links[/x]=/a/b, cwd=/, path=/x/../c → /a/c
(cycle) links[/a]=/b, links[/b]=/a, cwd=/, path=/a → must detect/avoid infinite loops (return an error or follow interviewer’s spec)
Example
Input
cwd=/a/b
path=../c
links=0
Output
/a/c