问题描述
Given an absolute path for a file (Unix-style), simplify it.
For example,
path ="/home/", =>"/home"
path ="/a/./b/../../c/", =>"/c"
click to show corner cases.
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".
问题分析
简化Unix下的文件路径,包括多余斜杠的去除,当前目录(./)的去除,以及父目录(../)的替代。
这题最好使用队列,先split,忽略””和”.”,处理好“..”就行了
代码实现
public String simplifyPath(String path) {
LinkedList<String> queue = new LinkedList<>();
StringBuilder result = new StringBuilder();
String[] str = path.split("/");
for (int i = 0; i < str.length; i++) {
if (str[i].equals("") || str[i].equals(".")) continue;
if (str[i].equals("..")) {
if (queue.isEmpty() == false) {
queue.pollLast();
}
} else queue.add(str[i]);
}
while (queue.isEmpty() == false) {
result.append("/");
result.append(queue.pollFirst());
}
if (result.length() == 0) return "/";
return result.toString();
}
网友评论