Given a string path, which is an absolute path (starting with a slash ‘/’) to a file or directory in a Unix-style file system, convert it to the simplified canonical path.
In a Unix-style file system, a period ‘.’ refers to the current directory, a double period ‘…’ refers to the directory up a level, and any multiple consecutive slashes (i.e. ‘//’) are treated as a single slash ‘/’. For this problem, any other format of periods such as ‘…’ are treated as file/directory names.
The canonical path should have the following format:
The path starts with a single slash ‘/’.
Any two directories are separated by a single slash ‘/’.
The path does not end with a trailing ‘/’.
The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period ‘.’ or double period ‘…’)
Return the simplified canonical path.
Example 1:
Input: path = “/home/”
Output: “/home”
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: path = “/…/”
Output: “/”
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: path = “/home//foo/”
Output: “/home/foo”
简单来说就是linux下路径简化问题。
思路:
路径简化有以下几种情况:
- 多个" / “可简化为一个” / "。
- " … “表示回到上一路径,比如”/home/leetcode/…“就是”/home", 这相当于把上一个leetcode给pop出来了。
- “.“表示当前路径,比如”/home/leetcode/.”, 那就是"/home/leetcode",可以看到"."没有任何作用,可以跳过
- 如果路径为空,认为就在根目录下,即" / "。
根据上面的情况,可以用" / “来split路径,提取split出来的字符串,然后用”/“连接这些字符串。
其中,”.“的字符串直接跳过,”…“就把前一个字符串pop掉,空字符串跳过(多个”/"简化为1个)。
public String simplifyPath(String path) {
Stack<String> stack = new Stack();
StringBuilder result = new StringBuilder();
String[

该博客主要讨论了如何在Linux风格的文件系统中对绝对路径进行简化,转化为规范路径。通过解析输入的路径字符串,处理'.'、'..'和连续的'/',将路径转化为不含冗余元素的形式。博主提供了两种不同的Java实现方式,一种使用栈,另一种用数组模拟栈,这两种方法都有效地实现了路径简化。
最低0.47元/天 解锁文章
540

被折叠的 条评论
为什么被折叠?



