-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathSolution.java
More file actions
41 lines (37 loc) · 1.04 KB
/
Solution.java
File metadata and controls
41 lines (37 loc) · 1.04 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package SimplifyPath;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* User: Danyang
* Date: 1/28/2015
* Time: 12:31
* Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
*/
public class Solution {
public String simplifyPath(String path) {
List<String> lst = Arrays.asList(path.split("/"));
List<String> stk = new ArrayList<>();
for(String elt: lst) {
if(elt.equals(".")) {
continue;
}
else if(elt.equals("..")) {
if(!stk.isEmpty())
stk.remove(stk.size()-1);
}
else if(elt.length()>0) {
stk.add(elt);
}
}
return "/"+stk.stream().collect(Collectors.joining("/"));
}
public static void main(String[] args) {
String ret = new Solution().simplifyPath("/..");
assert ret.equals("/");
}
}