思路:参考网上的讨论,用'/'作为分隔符,得到一系列子字符串 substr,有以下几种情况:
1)substr == "..",则表示需要返回上一级目录;
2)substr == "."或者 substr == "",不要做任何改变;
3)其他情况,则依次叠加表示的目录。
code:
class Solution {
public:
string simplifyPath(string path) {
string ret;
vector<string> temp;
string s;
path += "/";
int n = path.length();
for(int i = 0 ;i < n;i++){
if(path[i] == '/'){
if(s.empty() || s == "."){
s = "";
continue;
}
else{
if(s == ".."){
if(!temp.empty())
temp.pop_back();
}
else
temp.push_back(s);
}
s = "";
}
else{
s += path[i];
}
}
for(int i = 0;i < temp.size();i++){
ret += "/";
ret += temp[i];
}
if(ret.length() == 0) ret = "/";
return ret;
}
};我这里写复杂了,这篇博客有简洁的写法:
http://blog.youkuaiyun.com/maverick1990/article/details/23275051
本文介绍了一种使用C++实现的简化文件路径算法。通过分析路径字符串,并利用'/'作为分隔符来处理路径中的特殊符号如'..'和'.',最终达到规范化的路径表达。文章还提供了一个高效的代码实现方案。
2022

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



