Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Analysis
Code
public String simplifyPath(String path){
Deque<String> stack = new LinkedList<String>();
Set<String> skip = new HashSet<String>(Arrays.asList("..",".",""));
for(String dir : path.split("/")){
if (dir.equals("..") && !stack.isEmpty()){stack.pop();}
else if (!skip.contains(dir)) {stack.push(dir);}
}
String res = "";
for (String dir:stack) res = "/" + dir +res;
return res.isEmpty() ? "/" : res;
}
Note
- deque(double ended queue): use deque here since stack iterator does not behave as expected, see stackoverflow
- Arrays.asList(): provide a convenient way to create a fixed-size list initialized to several elements
- HashSet can be constructed with collection of specific elements
- String.split("")
Reference