https://oj.leetcode.com/problems/simplify-path/
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
- 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".
public String simplifyPath(String path)
这一题其实是之前Valid Number某种程度的简化版外加上Stack的应用。有一定的状态判断,另外要用Stack来保存遇到过的路径名。
特殊状态就两种"."和"..",而"/"是可以直接忽略的。
所以我们判断的时候遇到"/"就直接跳过,然后就判断是否以上两种状态之一,是前者也直接跳过,如果是后者就pop出一个Stack里面的一个路径名,如果两者皆非也不是"/",那么就是一个合法路径名,找到下一个"/"的位置,然后之前的字符串作为一个路径名放进stack里。到最后,根据stack的内容从后往前来得到整体的路径名。
public String simplifyPath(String path) {
Stack<String> pathstack = new Stack<String>();
for(int i = 0; i < path.length(); i++){
if(path.charAt(i) == '/'){
continue;
}else{
int tail = i;
while(tail < path.length() && path.charAt(tail) != '/')
tail++;
if(tail - i == 1 && path.charAt(i) == '.')
continue;
else if(tail - i == 2 && path.charAt(i) == '.' && path.charAt(i + 1) == '.'){
if(!pathstack.isEmpty())
pathstack.pop();
}
else
pathstack.push(path.substring(i, tail));
i = tail - 1;
}
}
String res = "";
while(!pathstack.isEmpty()){
res = "/" + pathstack.pop() + res;
}
if(res.isEmpty())
return "/";
return res;
}
Updated 2017-12-09 :
回顾了一下自己的答案以及参考了一下他人的,发现一个个字符扫真是一件很糟心的事儿。吃力不讨好。还不如一个String.split("/")省心。一个split直接判断当前子字符串是回退(".."),原地不动(空字符串或者一个点。空字符串实际上是遇到了连续两个"/"的情况),或者前进(其他字符串)。另外,用Deque在这里比Stack更适合,虽然我们存储的时候希望的是FILO(First In Last Out)的Stack,但是我们输出的时候希望的是一个FIFO的Queue,所以Deque就可以得到我们希望的目标。下面给出代码,比上面的答案简洁不少。另外注意的是Deque在Java里只是一个接口,其中一个实现就是LinkedList。我们这里用的是LinkedList
public String simplifyPath(String path) {
Deque<String> pathQueue = new LinkedList<String>();
String[] pathNodes = path.split("/");
for(String node : pathNodes) {
switch(node) {
case "..":
pathQueue.pollLast();
break;
case ".":
case "":
break;
default:
pathQueue.addLast(node);
}
}
StringBuilder builder = new StringBuilder();
if (pathQueue.isEmpty()) return "/";
while(!pathQueue.isEmpty()) builder.append("/" + pathQueue.removeFirst());
return builder.toString();
}
https://docs.oracle.com/javase/7/docs/api/java/util/Deque.html
276

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



