栈
- 思路:
- 遍历 path,如果是 '/',跳过,获取之后的目录;
- 通过上面过程,分割出了有效的目录集合,然后还原出路径;
- 通过 '/' 将每个目录连接还原出最简路径;
- 如果栈为空,则返回 '/';
class Solution {
public:
string simplifyPath(string path) {
std::vector<std::string> stk;
int size = path.size();
std::string dir = "";
for (int idx = 0; idx < size;) {
if (path[idx] == '/') {
++idx;
continue;
}
for (; idx < size && path[idx] != '/'; ++idx) {
dir += path[idx];
}
if (dir == ".") {
} else if (dir == "..") {
if (!stk.empty()) {
stk.pop_back();
}
} else {
stk.push_back(dir);
}
dir = "";
}
if (stk.empty()) {
return "/";
}
std::string simple_path = "";
for (auto & d : stk ) {
simple_path += ('/' + d);
}
return simple_path;
}
};