跳至主要内容

71. Simplify Path

class Solution {
public:
string simplifyPath(string path)
{
vector<string> dir;
stringstream ss(path);
string token;
while(getline(ss, token, '/'))
{
if(token == "..")
{
if (!dir.empty()) dir.pop_back();
}
else if (!token.empty() && token != ".")
{
dir.push_back(token);
}
}
string res;
for (auto s : dir) res += "/" + s;
return res.empty() ? "/" : res;
}
};
  • T: O(n)O(n)
  • S: O(n)O(n)