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 wherePath=
"/../"?
In this case, you shoshould return"/".
- Another corner case is the path might contain multiple slashes
‘/‘Together, such"/home//foo/".
In this case, you shoshould ignore redundant slashes and return"/home/foo".
The question is not difficult, mainly considering some special situations.
ForPath="/a/./b/../../c/", =>"/C", simulate
Split the string according to '/' to obtain [A,., B,..., C].
First, go to directory A. Note that '.' indicates the current directory, and ".." indicates the previous directory.
Then it reaches '.', still in the current directory,/
Then it reaches 'B', Which is/a/B.
Then, it reaches '..'. This is returned to the parent directory, and it becomes/.
Then, it reaches '..' and continues to return to the parent directory. Then it becomes/
Then it reaches 'C', and the sub-directory is reached to/C.
class Solution {public: vector<string> split(string& path, char ch){ int index = 0; vector<string> res; while(index < path.length()){ while(index < path.length() && path[index] == ‘/‘) index++; if(index >= path.length()) break; int start=index, len = 0; while(index < path.length() && path[index]!=‘/‘) {index++;len++;} res.push_back(path.substr(start,len)); } return res; } string simplifyPath(string path) { vector<string> a = split(path,‘/‘); vector<string> file; for(int i = 0 ; i < a.size(); ++ i){ if(a[i] == ".." ){ if(!file.empty()) file.pop_back(); } else if(a[i]!=".") file.push_back(a[i]); } string res=""; if(file.empty()) res ="/"; else{ for(int i = 0 ; i < file.size(); ++ i) res+="/"+file[i]; } return res; }};