[leetcode]simplify path

题目描述

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”.

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class {

public String simplifyPath1(String path) {
Deque<String> stack = new LinkedList<>();
Set<String> skip = new HashSet<>(Arrays.asList("..", ".",""));
for(String dir : path.split("/")){
if("..".equals(dir) && !stack.isEmpty()) stack.pop();
else if(!skip.contains(dir)) stack.push(dir);
}

// String res = "";
// for(String dir: stack){
// res = "/" + dir + res;
// }
StringBuilder res = new StringBuilder();

while(stack.peekLast() != null){
res.append("/");
res.append(stack.pollLast());
}

//return res.length() == 0 ? "/" : res;
return res.length() == 0 ? "/" : res.toString();

}
}

集合也可以不使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class {
//其实集合也可以不使用
public String simplifyPath(String path) {
Deque<String> stack = new LinkedList<>();
//Set<String> skip = new HashSet<>(Arrays.asList("..", ".",""));
for(String dir : path.split("/")){
// if("..".equals(dir) && !stack.isEmpty()) stack.pop();
// else if(!skip.contains(dir)) stack.push(dir);

if("..".equals(dir)){
if(!stack.isEmpty()) stack.pop();
}else if(!"".equals(dir) && !".".equals(dir)){
stack.push(dir);
}
}

String res = "";
for(String dir: stack){
res = "/" + dir + res;
}

return res.length() == 0 ? "/" : res;
}
}