Problem:
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"
.
Analysis:
Simulation problem, with the help of a vector keeping record of the current path and either push a new path node or pop the older path node or do nothing to maintain the final path.
Need to pay special attention to those corner cases.
Code:
1 class Solution { 2 public: 3 string simplifyPath(string path) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector<string> stack; 7 stack.push_back("/"); 8 9 int p1 = 0, p2 = 0; 10 while (true) { 11 while (path[p1] == '/' && p1<path.size()) 12 p1++; 13 14 p2 = p1+1; 15 while (path[p2] != '/' && p2<path.size()) 16 p2++; 17 18 if (p2 > path.size()) break; 19 20 string tmp = path.substr(p1, p2-p1); 21 if (tmp == "..") { 22 if (stack.size() != 1) 23 stack.pop_back(); 24 } 25 else if (tmp == ".") 26 ;//do nothing 27 else 28 stack.push_back(tmp); 29 30 p1 = p2; 31 } 32 33 34 if (stack.size() == 1) 35 return "/"; 36 else { 37 string tmp; 38 for (int i=1; i<stack.size(); i++) 39 tmp += "/" + stack[i]; 40 return tmp; 41 } 42 } 43 };