Given an absolute path for a file (Unix-style), simplify it.
For example,path =
"/home/"
, =>
"/home"
path = "/a/./b/../../c/"
, => "/c"
class Solution {
public:
/*algorithm
for simplicity, for path--> "#"+path + "/"
#/home/
"#/../"
*/
string simplifyPath(string path) {
vector<string>paths;
path = "#" + path +"/";
int i = 0,j;
while(i < path.size()){
j = i;
while(j < path.size() && path[j] != '/')++j;
string dir = path.substr(i,j-i);
if(dir == ".");
else if(dir == ".."){
if(paths.size() > 1)paths.pop_back(); //none root dir
}else
paths.push_back(dir);
while(j < path.size() && path[j]=='/')++j; //skip duplicate slash
i = j;
}
string sPath;;
for(int i = 0;i < paths.size();i++){
sPath += paths[i]=="#"?"":paths[i];
if(i==0 || i+1<paths.size())sPath += "/";
}
return sPath;
}
};