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 { //stack 2 public: 3 string simplifyPath(string path) { 4 string ans; 5 if(path[0]!='/') 6 return ans; 7 vector<string> vec; 8 int i=0,len=path.length(); 9 while(i<len) 10 { 11 int j=i+1; 12 while(j<len&&path[j]!='/') 13 j++; 14 15 string sub=path.substr(i+1,j-i-1); 16 if(sub.length()>0) 17 { 18 if(sub=="..") 19 { 20 if(!vec.empty()) 21 vec.pop_back(); 22 } 23 else if(sub!=".") 24 { 25 vec.push_back(sub); 26 } 27 } 28 i=j; 29 } 30 if(vec.empty()) 31 return "/"; 32 for(int k=0;k<vec.size();k++) 33 { 34 ans+="/"; 35 ans+=vec[k]; 36 } 37 return ans; 38 } 39 };