题目链接
法一
public String simplifyPath(String path) {
String[] items = path.split("/");
Deque<String> sk = new LinkedList<>();
for (String item : items) {
if (item.isEmpty() || item.equals(".")) {
continue;
} else if (item.equals("..")) {
if (!sk.isEmpty()) {
sk.pop();
}
} else {
sk.push(item);
}
}
StringBuilder sb = new StringBuilder();
while (!sk.isEmpty()) {
sb.insert(0, "/" + sk.pop());
}
if (sb.length() == 0) {
sb.append("/");
}
return sb.toString();
}
法二
public String simplifyPath_2(String path) {
String[] items = path.split("/");
Stack<String> sk = new Stack();
for (String item : items) {
if (item.isEmpty() || item.equals(".")) {
continue;
} else if (item.equals("..")) {
if (!sk.isEmpty()) {
sk.pop();
}
} else {
sk.push(item);
}
}
return "/" + String.join("/", sk);
}
本地测试
lay.showTitle(71);
Solution71 sol71 = new Solution71();
String path71 = "/a/./b/../../c/";
System.out.println(sol71.simplifyPath(path71));
System.out.println(sol71.simplifyPath_2(path71));