Question Definition
Given an absolute path for a file (Unix-style), simplify it. For example, path = “/home/”, => “/home” path = “/a/./b/../../c/”, => “/c”
Java Solution
public String simplifyPath(String path) {
Deque<String> deque = new ArrayDeque<>();
String[] paths = path.split("/");
for(String p : paths){
if(p.isEmpty() || p.equals(".")) continue;
if(p.equals("..")){
if(!deque.isEmpty())
deque.pop();
}else deque.push(p);
}
StringBuilder result = new StringBuilder();
while(!deque.isEmpty()){
result.insert(0, "/" + deque.pop());
}
return result.length() == 0 ? "/" : result.toString();
}
Comments