LeetCode71 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//bc/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系统下的一条文件路径,输出简化后的结果
思路是:
1.首先,题干里说如果有连续多个“/”,最后结果里都变成只有一个“/”,先用正则表达式去重,把连续2个以上“/”变成一个“/”。
2.把字符串按“/”拆分成数组arr,再变成集合list,注意字符串开头都是“/”,所以数组第一项会是“”,变成集合从第二项也就是arr[1]开始。
3.遍历集合,遇到“.”,代表当前目录,在简化后的路径里直接删除;遇到“…”,代表回退一个文件夹,即删除这个“…”和上一层文件夹,要注意此时索引是不是在最外面的文件夹,若是如此则没有上一层文件夹。
这里思路并不是很好,因为遍历集合同时删除元素会导致后面元素索引全部前移,所以每删除一个,遍历索引i要减一,否则下一次遍历会跳过下一个元素。同时循环终止条件要为list.size(),不能先算出len = list.size(),因为长度一直在变。
4.最后再遍历一次集合,把每一项前面加上“/”拼成字符串返回。
代码如下
public String simplifyPath(String path){
path = path.replaceAll("/{2,}", "/");
String[] arr = path.split("/");
List<String> list = new ArrayList<>();
for (int i = 1; i < arr.length; i++) {
list.add(arr[i]);
}
for (int i = 0; i < list.size(); i++) {
if(".".equals(list.get(i))){
list.remove(i);
i--;
}else if("..".equals(list.get(i))){
list.remove(i);
if(i > 0){
list.remove(i - 1);
i--;
}
i--;
}
}
StringBuilder sb = new StringBuilder();
int len = list.size();
if(len == 0){
sb.append("/");
}
for (int i = 0; i < len; i++) {
sb.append("/").append(list.get(i));
}
return sb.toString();
}
Beat了50%多结果,后来看别人的做法,基本都是用栈,replaceAll这个方法因为用到正则表达式,比较耗时。