Leetcode:71. Simplify Path
Description
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Corner Cases:
- Did you consider the case where path = "/../" In this case, you should return "/".
- Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". In this case, you should ignore redundant slashes and return "/home/foo".
思路
- 实现一个函数,每一次返回一个文件夹或文件名
- 若是"..",则保存路径的vector从末尾删除一个,代表跳到上一级目录
- 若是".","/","" 则什么都不做
- 若是正常文件名,则存入vector
代码
class Solution {
public:
string simplifyPath(string path) {
vector<string> res;
int len = path.size();
if (len == 0) return path;
int i = 0;
while (i < len){
string tmp = getNext(path, i, len);
if (tmp == ".."){
if (!res.empty()) res.pop_back();
}
else if (tmp == "." || tmp == "" || tmp == "/");
else res.push_back(tmp);
}
int s = res.size();
string str;
for (i = 0; i < s; ++i){
str += "/" + res[i];
}
return str == "" ? "/" : str;
}
string getNext(string& path, int &i, int len){
string res;
bool end = false;
while (i < len){
if (path[i] != '/')
res += path[i++];
else{
if (end){
break;
}
if (i + 1 < len && path[i + 1] == '/')
{
while (i + 1 < len && path[i + 1] == '/')
i++;
}
i++;
end = true;
}
}
return res;
}
};