71. Simplify Path(M)
1 Given an absolute path for a file (Unix-style), simplify it. 2 3 For example, 4 path = "/home/", => "/home" 5 path = "/a/./b/../../c/", => "/c" 6 click to show corner cases. 7 8 Corner Cases: 9 Did you consider the case where path = "/../"? 10 In this case, you should return "/". 11 Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/". 12 In this case, you should ignore redundant slashes and return "/home/foo".
1 class Solution { 2 public: 3 string simplifyPath(string path) { 4 deque<string> qs; 5 string result; 6 int plen = path.size(); 7 string::size_type curindex = 0, lastindex = 0; 8 9 while (lastindex < plen && (curindex = path.find("/", lastindex)) != string::npos) 10 { 11 if(path.find("//", lastindex)) 12 { 13 qs.push_back(path.substr(lastindex, curindex+1-lastindex)); 14 lastindex = curindex+2; 15 }else if (path.find("./", lastindex)) { 16 lastindex = curindex+1; 17 }else if (path.find(".//", lastindex)) { 18 lastindex = curindex+2; 19 }else if (path.find("../", lastindex)) { 20 qs.pop_back(); // go back one step 21 lastindex = curindex+1; 22 }else if (path.find("..//", lastindex)) { 23 qs.pop_back(); 24 lastindex = curindex+2; 25 }else { 26 qs.push_back(path.substr(lastindex, curindex+1-lastindex)); 27 lastindex = curindex+1; 28 } 29 } 30 31 while (!qs.empty()) { 32 string tmp = qs.front(); 33 qs.pop_front(); 34 result.append(tmp); 35 } 36 if(result.size() != 1){ 37 result.resize(result.size()-1); 38 } 39 return result; 40 } 41 };