class Solution {
public:
string simplifyPath(string path) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
stack<string> stk;
string str = "";
for (int i = 0; i < path.size(); ++i)
{
if (path[i] == '/')
{
if (str == "..")
{
if (!stk.empty()) stk.pop();
}
else if (str != "." && str != "")
{
stk.push(str);
}
str = "";
}
else
{
str += path[i];
}
}
if (str == "..")
{
if (!stk.empty()) stk.pop();
}
else if (str != "." && str != "")
{
stk.push(str);
}
if (stk.empty()) return "/";
string res = "";
while (!stk.empty())
{
res = "/" + stk.top() + res;
stk.pop();
}
return res;
}
};[Leetcode] Simplify Path
最新推荐文章于 2022-03-16 09:04:54 发布
本文介绍了一个C++实现的简化路径算法。该算法使用栈来处理输入的路径字符串,去除多余的'.'和'..'目录,并返回规范化后的路径。文章详细展示了如何逐字符扫描输入并根据特定规则更新栈。
1597

被折叠的 条评论
为什么被折叠?



