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".
class Solution { public: string simplifyPath(string path) { int l = path.size(), i, j; i = 0; string s; vector<string> v; while(i >= 0 && i < l) { while(path[i] == '/') i++; if(i >= l) break; j = path.find("/", i); if(-1 == j) s = path.substr(i); else s = path.substr(i, j-i); if(s == "..") { if(v.size()) v.erase(v.end()-1); } else if(s != ".") v.insert(v.end(), s); i = j; } if(!v.size()) return "/"; s = ""; for(i=0; i<v.size(); i++) { s += "/"; s += v[i]; } return s; } };
测试用例:
"/." -- "/"
"/../" -- "/"
"/home/" -- "/home"
"/a/./b/../../c/" -- "/c"
浙公网安备 33010602011771号