71. Simplify Path
by Botao Xiao
Question
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
path = "/a/../../b/../c//.//", => "/c"
path = "/a//b////c/d//././/..", => "/a/b/c"
In a UNIX-style file system, a period ('.') refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style
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”.
Thinking(二刷):
- Method 1: 实际上就是考察对栈进行运用,此时我们更倾向于使用LinkedList这种双向队列。
class Solution {
public String simplifyPath(String path) {
if(path == null || path.length() == 0) return "/";
LinkedList<String> stack = new LinkedList<>();
String[] tokens = path.split("/");
for(String token : tokens){
if(token.length() > 0){
if(token.equals(".")) continue;
else if(token.equals("..")){
if(!stack.isEmpty()) stack.pollLast();
}else{
stack.add(token);
}
}
}
StringBuilder sb = new StringBuilder();
if(stack.isEmpty()) return "/";
while(!stack.isEmpty()){
sb.append("/");
sb.append(stack.pollFirst());
}
return sb.toString();
}
}
Subscribe via RSS