-
The path does not end with a trailing '/'.
-
The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period '.' or double period '..')
Return the simplified canonical path.
Example 1:
Input: path = “/home/”
Output: “/home”
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
Input: path = “/…/”
Output: “/”
Explanation: Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
Example 3:
Input: path = “/home//foo/”
Output: “/home/foo”
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: path = “/a/./b/…/…/c/”
Output: “/c”
Constraints:
-
1 <= path.length <= 3000
-
path consists of English letters, digits, period '.', slash '/' or '_'.
-
path is a valid absolute Unix path.
[](()Analysis
略
[](()Submission
import java.util.LinkedList;
public class SimplifyPath {
// 方法一:我写的
public String simplifyPath(String path) {
LinkedList dirs = new LinkedList<>();
for (int p1 = 0, p2 = 1; p2 <= path.length(); p2++) {
if (p2 == path.length() || path.charAt(p2) == ‘/’) {
String dir = path. 《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》无偿开源 威信搜索公众号【编程进阶路】 substring(p1 + 1, p2);
p1 = p2;
if (dir.equals(“”) || dir.equals(“.”))
continue;
if (dir.equals(“…”)) {
if (!dirs.isEmpty())
dirs.removeLast();
} else {
dirs.add(dir);
}
}
}
StringBuilder sb = new StringBuilder();
dirs.stream().forEach(dir -> sb.append(“/”).append(dir));
return sb.length() == 0 ? “/” : sb.toString();
}
// 方法二:别人写的,写得更简洁
public String simplifyPath2(String path) {
LinkedList list = new LinkedList<>();



