Simplify Path
题目
题目链接:https://leetcode.com/problems/simplify-path
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:
Input: "/home/"
Output: "/home"
Explanation: Note that there is no trailing slash after the last directory name.
Example 2:
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:
Input: "/home//foo/"
Output: "/home/foo"
Explanation: In the canonical path, multiple consecutive slashes are replaced by a single one.
Example 4:
Input: "/a/./b/../../c/"
Output: "/c"
Example 5:
Input: "/a/../../b/../c//.//"
Output: "/c"
Example 6:
Input: "/a//bc/d//././/.."
Output: "/a/b/c"
分析
给出一个Linux/Unix风格的绝对路径,要简化该路径。即将其转化成为一个标准的路径。
我们知道,在Linux/Unix中,路径名是以/
开头的。.
表示当前目录,..
表示上一层目录。/
表示根目录,其上一层目录仍然为根目录/
。不能以/
结尾(根目录只有一个/
)。
需要注意的是,连续出现n个/
,实际上也仅仅代表一个/
,例如/home///user
其实就是/home/user
。
因此,我们可以使用/
分割当前字符串,然后遍历得到的字符串数组。
对于第i
个字符串:
- 当该字符串是空串
""
或者是"."
,路径不变。 - 当该字符串是
".."
时,表示上一层路径,此时删除结果字符串最后一个目录。如果结果字符串为""
,则保持不变。 - 其他情况下,添加
/
和当前字符串的值到结果字符串中。
最后,当结果字符串的长度为0
时,添加/
,然后返回。不为0
时直接返回。
代码如下
class Solution {
public String simplifyPath(String path) {
StringBuilder result = new StringBuilder();
String[] strings = path.split("/");
for (int i = 0; i < strings.length; i++) {
if (strings[i].equals("") || strings[i].equals(".")) {
continue;
} else if (strings[i].equals("..")) {
int index = result.lastIndexOf("/");
if (index >= 0) {
result.delete(index, result.length());
}
} else {
result.append('/');
result.append(strings[i]);
}
}
if (result.length() == 0) {
result.append('/');
}
return result.toString();
}
}