题目:
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
click to show corner cases.
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”.
题意:
给一个绝对路径(Unix风格的),简化这个路径。比如最后加一个’/’就可以去掉,在unix
中,’./’代表的是当前文件夹位置,’../’代表的是上次文件夹位置。
思路:
通过一个vector存放路径,如果遇到’.’,如果遇到’..’就从vector中退出一个末端的string,如果遇到字符串,就存入到vector末端。”/../”这种风格直接返回“/”,出现连着的/去掉重复的即可。
特例有:”/…”,”/..hidden”,”/…/”
以上。
代码如下:
class Solution {
public:
string simplifyPath(string path) {
if (path.size() == 0)return "";
// else if(path == "/..." || path == "/.../")return "/...";
vector<string> result;
path += "/";
int i = 0;
while (i < path.size() && path[i] == '/')i++;
int j = i + 1;
int countDot = (path[i] == '.') ? 1 : 0;//if is dot or not
int countChar = (path[i] == '.') ? 0 : 1;//if is char or not
while (j < path.size()){
switch (path[j]){
case '.':{
countDot++;
break;
}
case '/':{
if (countChar != 0){
result.push_back(path.substr(i, countChar + countDot));
countChar = 0;
}
else if (countDot != 0){
if (countDot == 2 && !result.empty())result.pop_back();
else if(countDot > 2)
result.push_back(string(countDot,'.'));
countDot = 0;
}
while (j < path.size() && path[j] == '/'){
j++;
}
countDot = (path[j] == '.') ? 1 : 0;//if is dot or not
countChar = (path[j] == '.') ? 0 : 1;//if is char or not
i = j;
break;
}
default:{
countChar++;
break;
}
}
j++;
}
string res = "";
for (int i = 0; i < result.size(); i++)
res += ("/" + result[i]);
return (res == "") ? "/" : res;
}
};