71. Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
path = "/a/../../b/../c//.//", => "/c"
path = "/a//b////c/d//././/..", => "/a/b/c"
In a UNIX-style file system, a period ('.') refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style
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 = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
边界情况:
你是否考虑了 路径 = "/../" 的情况?
在这种情况下,你需返回 "/" 。
此外,路径中也可能包含多个斜杠 '/' ,如 "/home//foo/" 。
在这种情况下,你可忽略多余的斜杠,返回 "/home/foo" 。
【思路】
思路很简单,实现起来想提高时间复杂度有点困难。我使用了两种方法,结果都很不理想。第一种是,使用stack,先把传入的path进行split("/"),这个时候我们得到一个数组,接下来对特殊字符进行处理,就是"."和"..",遇到.直接跳过,遇到“..”将存入stack中的数据出栈,遇到别的,入栈。当遍历完成,将会得到路径的栈,此时将其中间加上“/”即可。执行效率不高。另外一种想法,直接用字符串代替栈,性能仍然不好。
【代码】
public String simplifyPath(String path) {
String[] values = path.split("/");
Stack<String> stack = new Stack<String>();
for(String value : values)
if(value.equals(".")||value.equals(""))
continue;
else if (value.equals("..")){
if(!stack.isEmpty())
stack.pop();
}
else
stack.push(value);
if(stack.isEmpty())
return "/";
String returnString = "";
while(!stack.isEmpty())
returnString = "/" + stack.pop() + returnString;
return returnString;
}