Write a function that takes a string input. The string will be a file path name (for example, /usr/bin). The path may contain special directories . (reference to self) and .. (reference to parent directory). Your function should return the path without using these special directories.
Example input/output
Input: "/etc/tmp" -> [etc, tmp]
Output: "/etc/tmp"
Input: "/usr/bin/./some_file.sh" -> [usr, bin, ., some_file.sh]
Output: "/usr/bin/some_file.sh"
Input: "/usr/bin/../local"
Output: "/usr/local"
这道题考查的是 Unix 风格路径简化。核心思路是按“/”分割路径,使用栈或动态数组依次处理每一段:遇到普通目录就入栈,遇到“.”直接跳过,遇到“..”则弹出上一级目录(如果栈非空)。最后把栈中的目录重新用“/”拼接即可。注意要正确处理连续斜杠、开头斜杠以及回退到根目录的边界情况。
正文完