The idea of this question is still clear. If we use stacks, the trouble is that we have to deal with the details of these layers. There are mainly the following:
./And/: the current path. In this case, the following folders or files should be put into the stack.
../: The path of the previous layer. In this case, an out-of-stack operation should be performed, which is equivalent to returning the directory of the previous layer.
//: It can be directly simplified '/'.
There are also several test cases worth attention:
1. linux pathnames can contain many special characters, such as "_", ".", "*", etc. Pay special attention to which pathnames contain.
2. You do not need to append '/' to the... And .. at the end of the path.
The code is not well written. You should correct it later:
class Solution {public: string simplifyPath(string path) { stack<string> s; int len = path.length(); int i=0; string tp, res=""; while(i<len){ if(path[i] == '/'){i++;} else if(isalnum(path[i])||path[i]=='_'){ int j=i+1; while(path[i-1]=='.') i--; while((isalnum(path[j])||path[j]=='_')&&j<len) j++; tp = path.substr(i, j-i); s.push(tp); i = j; }else if(path[i] == '.'){ if(i+1==len) break; else if(path[i+1]=='/') i = i+2; else if(path[i+1]=='.'){ if(path[i+2] == '/'||i+2==len){ i = i+3; if(!s.empty())s.pop(); }else if(path[i+2] == '.'){ if(i+3==len||path[i+3] == '/') s.push("..."); i = i+3; }else i = i+2; }else i = i+1; } } if(s.empty()) res = "/"; else{ while(!s.empty()){ res = "/"+s.top()+res; s.pop(); } } return res; }};