题目要求简化Unix路径。即把路径中的..
和多余的/
简化。
用一个栈parse输入路径即可。
代码:
string simplifyPath(string path) {
path += "/";
int len = path.length();
stack<string> directory;
string cur;
for(int i = 0 ; i < len ; i++) {
if(path[i] == '/') {
if(cur == ".") {
cur = "";
}
else if(cur == "..") {
if(!directory.empty())
directory.pop();
cur = "";
}
else if(cur != "") {
directory.push(cur);
cur = "";
}
}
else {
cur += path[i];
}
}
string newpath;
while(!directory.empty()) {
if(newpath == "")
newpath = directory.top();
else
newpath = directory.top() + "/" + newpath;
directory.pop();
}
newpath = "/" + newpath;
return newpath;
}