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"
.
Runtime: 6ms
1 class Solution { 2 public: 3 string simplifyPath(string path) { 4 string newPath; 5 vectordirectory; 6 stringstream newString(path); 7 string temp; 8 while (getline(newString, temp, '/')) { 9 if (temp == "." || temp == "") continue;10 else if (temp == ".." && !directory.empty()) directory.pop_back();11 else if (temp != "..") directory.push_back(temp);12 }13 14 for (string current : directory) {15 newPath += "/" + current;16 }17 return newPath.empty() ? "/" : newPath;18 }19 };