class Solution {
public:
string simplifyPath(string path) {
deque<string>st;
int i=0, n=path.length();
string res;
while(i<n){
//分割任意多个连续的斜杠之间的文件名
while(i<n && path[i]=='/') i++; //跳过任意多个连续的斜杠
string temp;
while(i<n && path[i]!='/') //截取到temp文件名称
temp+=path[i++];
//判断如何处理这一次的文件路径
if(temp==".." && !st.empty()) //如果".."且有上一级目录需要弹出
st.pop_back();
//当前目录、 .. 但没有上一级目录、 空文件名 则不需要压入
else if(temp!="." && temp!=".." && temp!=""){
st.push_back(temp);
}
}
for(string s:st) //串联起简化路径
res+=('/'+s);
if(st.empty()) res="/"; //没有路径则"/""
return res;
}
};
71. 简化路径
最新推荐文章于 2024-05-07 09:26:54 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)