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".
classSolution { public: string simplifyPath(string path){ int n = path.length(); stack<string> q;
for (int i = 1; i < n; ){ if (path[i] == '.'){ if (i + 1 < n && path[i + 1] == '.' && (i+2>=n ||i+2<n&& path[i+2]=='/')){ if (!q.empty()) q.pop(); i += 3; continue; } elseif (i + 1 < n && path[i + 1] == '/'){ i += 2; continue; } } int cur = path.find_first_of('/', i); if (cur == -1){ string temp = path.substr(i, n - i); if (temp != " " && temp != "." && temp != "..") q.push(temp); break; } if (cur!=i) q.push(path.substr(i, cur - i)); while (cur + 1 < n && path[cur + 1] == '/') cur++; i = cur + 1; } stack<string> q2; while (!q.empty()){ q2.push(q.top()); q.pop(); } string ans="/"; while (!q2.empty()){ ans = ans + q2.top(); q2.pop(); if (!q2.empty()) ans = ans + '/'; } return ans; } };
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution: # @param path, a string # @return a string defsimplifyPath(self, path): q=path.split('/') ans=[] for s in q: if s: if s=='..': iflen(ans) > 0: ans.pop() elif s!='.': ans.append(s) return'/'+'/'.join(ans)