Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
汗!不熟悉linux啊,'.'是当前目录,‘..’是到上一级目录。其他的都没有特殊含义。
class Solution {
public:
string simplifyPath(string path) {
stack<string> words;
path += '/';
string current;
for(int ii = 0; ii < path.length(); ii ++) {
if(path[ii] != '/') {
current += path[ii];
}
else {
if(current.length() == 1 && current[0] == '.') {
current.clear();
continue;
}
if(current.length() == 2 && current[0] == '.' && current[1] == '.') {
if(!words.empty()) {
words.pop();
}
current.clear();
continue;
}
if(!current.empty()) {
words.push(current);
current.clear();
continue;
}
}
}
string result;
while(!words.empty()) {
result = '/' + result;
result = words.top() + result;
words.pop();
}
if(!result.empty()) {
result = result.substr(0, result.length() - 1);
}
result = "/" + result;
return result;
}
};
本文深入探讨了如何将Unix风格的绝对路径进行简化的过程,详细解释了'.(当前目录)'和'..(上一级目录)'符号的作用,并通过C++代码实例展示了实现路径简化的步骤。
1584

被折叠的 条评论
为什么被折叠?



