简化unix文件路径
1. 分割提取+栈
class Solution {
public:
string simplifyPath(string path) {
vector<string> names = split(path, '/');//消除/并得到待处理的多段文件名
vector<string> stack;//这里需要使用栈来判断..的回跳
for (string& name: names) {
if (name == ".."){
if(!stack.empty()) stack.pop_back();//回跳到上一级目录
}
else if (!name.empty() && name != ".") //不处理空字符串和单点
stack.push_back(name);//当前目录入栈
}
string ans;
if (stack.empty()) return "/";//没有访问子目录
for (string& name: stack) //拼接剩余的目录
ans += "/" + name;
return ans;
}
vector<string> split (string& s, char delim) {//根据字符划分字符串
vector<string> ans;
string cur;
for (char ch: s) {
if (ch == delim) {//碰到了分隔符
ans.push_back(cur);
cur.clear();
}
else cur += ch;
}
ans.push_back(cur);
return ans;
};
};
标签:back,name,路径,cur,stack,简化,ans,LeetCode,string
From: https://www.cnblogs.com/929code/p/17372719.html