For example,
path =
"/home/", => "/home"path =
"/a/./b/../../c/", => "/c"Use split to split the path according to "/+". Then swap the entire array and maintain a stack. We do the following:
- If we encounter a ""(this might happen due to the first character of the path is "/") or a ".", we continue.
- If we encounter a "..", if there are something in the stack, we pop one out.
- Otherwise we push the string into the stack.
public String simplifyPath(String path) {
int n = path.length();
if(n == 0)
return "/";
String[] strs = path.split("/+");
List<String> stack = new ArrayList<String>();
for(int i = 1; i < strs.length; i++) {
if(strs[i].equals("."))
continue;
else if(strs[i].equals("..")) {
if(stack.size() != 0)
stack.remove(stack.size() - 1);
}
else
stack.add(strs[i]);
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < stack.size(); i++) {
sb.append("/");
sb.append(stack.get(i));
}
if(stack.size() == 0) // corner case, if the stack is empty, should return "/" not ""
return "/";
return sb.toString();
}
没有评论:
发表评论