71. 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. For more information, see: Absolute path vs relative path in Linux/Unix
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//b////c/d//././/.."
Output: "/a/b/c"
C++ 实现 1
在编写代码之前, 可以多检查一些例子:
path = "/home/../", => "/"
path = "/a/./b/../c/", => "/a/c"
path = "/a/./b/c/", => "/a/b/c"
首先, 处理路径我们可以考虑用栈. 我考虑用栈来保存真实的目录, 比如 home
, a
, b
, c
之类的, 而不保存空字符, 或者 .
以及 ..
, 另外也不保存 /
.
如果遇到 ..
, 那么检查栈是否不为空, 如果不为空, 将最近的目录给弹出来; 否则不做任何处理;
如果遇到 .
, 那么也不做任何处理;
如果遇到既不是 .
也不是 ..
的真实目录, 则将该目录入栈;
另外对于 //
的处理就是略过.
使用 i
和 j
来检查 path[i, j)
是否为真实的目录. 另外, 栈不一定要用 stack
来实现, vector
也行.
class Solution {
public:
string simplifyPath(string path) {
vector<string> st;
int i = 1;
while (i < path.size()) {
int j = i;
while (j < path.size() && path[j] != '/') ++ j;
if (j == i) ++ i; // 遇到了 `//` 的情况
else {
auto dir = path.substr(i, j - i);
if (dir == ".." && st.size() > 0) st.pop_back();
else if (dir != ".." && dir != ".") st.push_back(dir);
i = ++ j;
}
}
string res = "/";
for (auto &dir : st)
res += dir + "/";
return res.size() > 1 ? res.substr(0, res.size() - 1) : res;
}
};
C++ 实现 2
两年前的代码. C++ 中可以使用 stringstream 来处理字符串, 而 getline 函数的最后一个参数可以设置 delimiter. 代码如下:
- http://www.cnblogs.com/grandyang/p/4347125.html
- https://leetcode.com/problems/simplify-path/discuss/25680/C+±10-lines-solution
class Solution {
public:
string simplifyPath(string path) {
vector<string> stk;
stringstream ss(path);
string res;
string tmp;
// 如果 tmp 为空或者为 ., 那么直接略过
// 如果 tmp 为 .., 那么将上一层挨着的路径给略过
// 将所有不为 .. 的字符存入到 stk 中
while (getline(ss, tmp, '/')) {
if (tmp == "" || tmp == ".") continue;
if (tmp == ".." && !stk.empty()) stk.pop_back();
else if (tmp != "..") stk.push_back(tmp);
}
for (auto &str : stk) res += "/" + str;
return res.empty() ? "/" : res;
}
};