LeetCode Link
string simplifyPath(string path) {
stack<string> stk;
stringstream ss(path);
string token;
while (getline(ss, token, '/')) {
if (token == "" || token == ".") {
continue;
}
if (token == "..") {
if (!stk.empty()) {
stk.pop();
}
} else {
stk.push(token);
}
}
vector<string> components;
while (!stk.empty()) {
components.push_back(stk.top());
stk.pop();
}
reverse(components.begin(), components.end());
string result = "/";
for (const string& component : components) {
result += component + "/";
}
if (result.size() > 1) {
result.pop_back();
}
return result;
}