/*细节模拟题。
参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
string simplifyPath(string path) {
string res;
vector<string> path_name;
string::iterator it = path.begin();
while(it != path.end()){
++it;
string::iterator itt = find(it, path.end(), '/');
string dir(it, itt);
if(!dir.empty() && dir != "."){//dir为有效目录
if(dir == ".."){//返回上级目录
if(!path_name.empty()) path_name.pop_back();
}
else{
path_name.push_back(dir);
}
}
it = itt;
}
if(path_name.empty()) return "/";
for(int i = 0; i < path_name.size(); ++i)
res = res + "/" + path_name[i];
return res;
}
};LeetCode之Simplify Path
最新推荐文章于 2022-03-16 09:04:54 发布
本文介绍了一个C++实现的路径简化算法,该算法通过解析输入的文件路径字符串并利用栈来实现目录层级的递归处理,最终返回规范化的路径。具体而言,它会忽略无效的目录名如.和空字符串,并在遇到..时返回上一级目录。
1597

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



