题目描述
这同样也是leetcode上的题。原题链接
Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.
In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period … moves the directory up a level.
Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.
Example 1:
Input: “/home/”
Output: “/home”
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: “/…/”
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: “/home//foo/”
Output: “/home/foo”
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
问题分析
简化路径是一个十分实际的问题,在平常是使用中也经常能用到。那么如何使用栈来化简绝对路径?
首先将问题化简一下。假设路径已经是最简的情况了,那么我们需要有一种方法来用栈来表示路径。在这,我选择用string 栈来表示路径。而由于栈的后进先出的特点,我们需要将路径反着存入栈中,存入时,在其前方加入路径分隔符’/’。因此,可以从后向前遍历题目所给的字符串路径。而这需要指出的是,其获得的目录名是倒序的字符串,所以将该字符串存入栈的时候需要将字符串反转。等输出路径时,我们只需依次弹栈的时候,就可以得到正确的路径。
现在考虑一下路径并非最简的情况。首先,当目录为"." 时,表示的是目录本身,因此可将之忽略。然后,当目录为“. .”时,表示的是其父目录。由于在用栈来表示路径的情况下其父目录根本不在栈中,我们只能将之先存入栈中。相应的,我们需要每次压栈的时候需要考虑栈顶是否为". ."。若是,则将之弹栈。不过,这里特殊情况。若要压栈的目录也是". .“的时候,需要将之压栈而并非弹栈。最后,便是路径的输出。由于路径并非最简,还要注意两点。一是根目录无父目录,因此”/. .“表示的是”/",所以当最后弹栈的时候若其栈顶元素为"/. .“时,应不将之加入路径中。其次,路径不应该为空。所以若最后所得路径为空,应输出根目录”/"。
我的话可能表述得并不清晰明了,但是可以看我的代码来明白我的意思。
代码实现
public String simplifyPath(String path) {
Stack<String> pathStack = new Stack<>();
int i = path.length() - 1;
StringBuilder sb = new StringBuilder();
while (i >= 0) {
char getc = path.charAt(i);
if (getc == '/') {
if (!sb.toString().isEmpty()) {
if (sb.toString().equals(".")) {
sb = new StringBuilder();
} else {
if (!pathStack.isEmpty()) {
if (pathStack.peek().equals("/..") && !sb.toString().equals("..")) {
sb = new StringBuilder();
pathStack.pop();
i--;
continue;
}
}
pathStack.push("/" + sb.reverse().toString());
sb = new StringBuilder();
}
}
} else {
sb.append(getc);
}
i--;
}
sb = new StringBuilder();
while (!pathStack.empty()) {
String pa = pathStack.pop();
pa = pa.equals("/..") ? "" : pa;
sb.append(pa);
}
if (sb.toString().isEmpty()) {
sb.append("/");
}
return sb.toString();
}
336




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



