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".
1 class Solution { 2 public: 3 string simplifyPath(string path) { 4 int n = path.size(); 5 stack<string> s; 6 string dir; 7 for (int i = 0; i < n; i++) { 8 if (path[i] == '/') { 9 if (!dir.empty()) { 10 s.push(dir); 11 dir.clear(); 12 } 13 } else { 14 dir.push_back(path[i]); 15 } 16 } 17 if(!dir.empty()) s.push(dir); 18 19 string res; 20 int count = 0; 21 while (!s.empty()) { 22 string str = s.top(); 23 s.pop(); 24 if (str == ".") { 25 continue; 26 } else if (str == "..") { 27 count++; 28 } else { 29 if (count > 0) { 30 count--; 31 } else { 32 res = "/" + str + res; 33 } 34 } 35 } 36 if(res.length() == 0) return "/"; 37 return res; 38 } 39 };