
Desicription
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
class { public: string simplifyPath(string path) { vector<string> nameVect; string name; path.push_back('/'); for(int i=0;i<path.size();i++){ if(path[i]=='/'){ if(name.size()==0)continue; if(name==".."){ if(nameVect.size()>0)nameVect.pop_back(); }else if(name=="."){ }else{ nameVect.push_back(name); } name.clear(); }else{ name.push_back(path[i]); } }
string result; if(nameVect.empty())return "/"; for(int i=0;i<nameVect.size();i++){ result.append("/"+nameVect[i]); } return result; } };
|
近期评论