题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
click to show corner cases.
Corner Cases:
Did you consider the case where path = "/../"?
In this case, you should return "/".
Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".
解答:
unix style path的规则如下:
/ -> root
/a -> in (a)
. -> THIS dir path
/a/./ -> still in /a
/a/./b -> in /a/b
.. -> go "up" one level
/a/./b/.. -> /a/b/.. -> /a
/a/./b/../.. -> /a/.. -> /
/a/./b/../../c -> /c
public class Solution {
public String simplifyPath(String path) {
Stack<String> stack = new Stack<String>();
//三种需要跳过的情况
Set<String> skip = new HashSet<String>(Arrays.asList("..", ".", ""));
for (String dir : path.split("/")) {
//当遇到..时,需要向前进
if (dir.equals("..") && !stack.isEmpty()) {
stack.pop();
} else if (!skip.contains(dir)) {
stack.push(dir);
}
}
String result = "";
if (stack.isEmpty()) result += "/";
while (!stack.isEmpty()) {
//pop出来的顺序是反的,所以加的时候,把最新pop出来的路径加在前面
result = "/" + stack.pop() + result;
}
return result;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。