题目:
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" Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Constraints:
1 <= path.length <= 3000
path
consists of English letters, digits, period'.'
, slash'/'
or'_'
.path
is a valid absolute Unix path.
题解:
class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
String[] components = path.split("/");
for(String directory : components){
if(directory.equals(".") || directory.isEmpty()){
continue;
} else if(directory.equals("..")){
if(!stack.isEmpty()){
stack.pop();
}
} else{
stack.add(directory);
}
}
StringBuilder result = new StringBuilder();
for(String dir : stack){
result.append("/");
result.append(dir);
}
return result.length() == 0 ? "/" : result.toString();
}
}
- 初始化一个堆栈,S我们将用于我们的实现。
- 使用分隔符拆分输入字符串 “/” 。这一步非常重要,因为无论如何,给定的输入是一条合理路径,我们只需要缩短它。因此,这意味着我们在两个 ‘/’ 字符之间的任何内容都是目录名称或特殊字符,我们必须相应地处理它们。
- 一旦我们完成了输入路径的分割,我们将一次处理一个组件。
- 如果当前组件是一个 ‘.’ 或一个空字符串,我们什么也不做,继续。好吧,如果您考虑一下,字符串的拆分字符串数组/a//b将是[a,,b],那是a和b之间的空字符串。同样,从整体路径的角度来看,它没有任何意义。
- 如果我们遇到双点..,我们必须做一些处理。这只是意味着在当前目录路径中上一级。因此,如果它不为空,我们将从堆栈中弹出一个条目。
- 最后,如果我们现在正在处理的组件不是特殊字符之一,那么我们将简单地将它添加到我们的堆栈中,因为它是一个合法的目录名称。
- 处理完所有组件后,我们只需使用/分隔符将堆栈中的所有目录名称连接在一起,我们将拥有最短路径,将我们引导到与作为输入提供的目录相同的目录