用栈保存化简后的路径。把原始路径根据"/"切分成若干小段,然后依次遍历
若当前小段是"..",弹栈
若当前小段是".",什么也不做
否则,入栈
代码:
string simplifyPath(string path) {
vector<string> buffer;
char *tok = NULL; tok = strtok((char *) path.c_str(), "/");
while (tok) {
cout << tok << endl;
if (strcmp(tok, "..") == ) {
if (!buffer.empty())
buffer.pop_back();
}
else if (strcmp(tok, ".") != )
buffer.push_back(string(tok));
tok = strtok(NULL, "/");
} string res;
for (auto dir : buffer)
res += "/" + dir;
return buffer.empty() ? "/" : res;
}