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;
}
};