Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
simplify-path.cpp 1.19 KB
一键复制 编辑 原始数据 按行查看 历史
// Time: O(n)
// Space: O(n)
class Solution {
public:
string simplifyPath(string path) {
vector<string> names;
vector<string> tokens(move(split(path, '/')));
for (const auto& token : tokens) {
if (token == ".." && !names.empty()) {
names.pop_back();
} else if (token != ".." && token != "." && !token.empty()) {
names.emplace_back(token);
}
}
return string("/").append(join(names, '/'));
}
private:
// Split string by delimitor.
vector<string> split(const string& s, const char delim) {
vector<string> tokens;
stringstream ss(s);
string token;
while (getline(ss, token, delim)) {
tokens.emplace_back(token);
}
return tokens;
}
// Join strings with delimitor.
string join(const vector<string>& names, const char delim) {
ostringstream ss;
if (!names.empty()) {
const string delim_str(1, delim);
copy(names.cbegin(), prev(names.cend()),
ostream_iterator<string>(ss, delim_str.c_str()));
ss << names.back();
}
return ss.str();
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助