71. Simplify Path Medium

Given an absolute path for a file (Unix-style), simplify it. Or in other words, convert it to the canonical path.

In a UNIX-style file system, a period . refers to the current directory. Furthermore, a double period .. moves the directory up a level.

Note that the returned canonical path must always begin with a slash /, and there must be only a single slash / between two directory names. The last directory name (if it exists) must not end with a trailing /. Also, the canonical path must be the shortest string representing the absolute path.

Example 1:

1
2
3
Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.

Example 2:

1
2
3
Input: "/../"
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:

1
2
3
Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.

Example 4:

1
2
Input: "/a/./b/../../c/"
Output: "/c"

Example 5:

1
2
Input: "/a/../../b/../c//.//"
Output: "/c"

Example 6:

1
2
Input: "/a//b////c/d//././/.."
Output: "/a/b/c"

思路:

思路一:栈

这两个思路是一样的,只是分别使用数组和栈而已

  • 首先从 / 分开,然后用栈保存,如果栈不为空,且当前字符为 .. 说明要进行进入上层目录,此时将栈中的元素弹出
  • 只要不为空、不为 . 、不为 .. ,就把其中的元素放入栈中即可
  • 最后在最前面和每个字符串中间加上 /

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public String simplifyPath(String path) {
// 1. Stack
String[] split = path.split("/");
Stack<String> stack = new Stack<>();
for (String s : split) {
if (!stack.isEmpty() && "..".equals(s)) {
stack.pop();
}
else if (!".".equals(s) && !"".equals(s) && !"..".equals(s)) {
stack.push(s);
}
}
List<String> res = new ArrayList<>(stack);
return "/" + String.join("/", res);
}

时间复杂度:O(n)

空间复杂度:O(n)

思路二:纯数组

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public String simplifyPath(String path) {
String[] split = path.split("/");
List<String> wordList = new ArrayList<>();
for (String s : split) {
if (s.isEmpty() || s.equals(".")) {
continue;
}
wordList.add(s);
}
List<String> wordListSim = new ArrayList<>();
for (String s : wordList) {
if (s.equals("..")) {
if (!wordListSim.isEmpty()) {
wordListSim.remove(wordListSim.size() - 1);
}
} else {
wordListSim.add(s);
}
}
return "/" + String.join("/", wordListSim);
}

评论