Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
去掉.;删掉多余的/;当遇见..时要返回上一级目录
所以,使用一个栈保存中间结果。最后不要忘记只有“/”的情况。打印时,记得从栈的尾部开始。
class Solution {
public String simplifyPath(String path) {
String[] list = path.split("/");
LinkedList<String> stack = new LinkedList<>();
//System.out.println(Arrays.asList(list));
for (int i = 0; i < list.length; i++) {
if (list[i].equals(""))
continue;
if (list[i].equals("."))
continue;
if (list[i].equals("..")) {
if (!stack.isEmpty()) {
stack.pop();
}
} else {
stack.push(list[i]);
}
}
if (stack.isEmpty())
return "/";
StringBuilder sb = new StringBuilder();
while (!stack.isEmpty()) {
sb.append("/");
sb.append(stack.pollLast());
}
return sb.toString();
}
}