一、问题描述
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
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"
.
二、问题分析
Corner cases给出了很多需要考虑的点。"/a/./b/../../c/"
, => "/c"
分析过程:先是a,然后‘.’路径不变,再是b变为/a/b,接下来‘..’,变为/a等等,我们可以发现所有的操作均是在路径的尾,考虑一下只有一头操作的数据结构,我们会发现stack刚好符合。然后我们需要考虑的就是如何获取/xxx/中xxx的部分,容易发现字符串以‘/’来分割,因此可以使用split方法。时间复杂度为O(n)。
三、Java AC代码
public String simplifyPath(String path) {
StringBuilder sb = new StringBuilder();
LinkedList<String> stack = new LinkedList<String>();
String[] strs = path.split("/+");
for (String str : strs) {
if (str.equals("") || str.equals(".")) {
continue;
}
if (str.equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else if (!str.equals(".")) {
stack.push(str);
}
}
if (stack.isEmpty()) {
return "/";
}
while(!stack.isEmpty()){
sb.append("/"+stack.removeLast());
}
return sb.toString();
}