原题链接:71. 简化路径
solution:
① 以'/'为分隔符分割字符串,这样就可以提取'/'间有效的内容,保存在items中
② 利用栈的性质,遍历items,如果遇到的不是'.'、'..'和空字符串就把内容入栈,如果遇到的是'..'就把栈顶内容弹出。
③ 最后保存答案
class Solution {
public:
string simplifyPath(string path) {
vector<string> items = split(path, '/');
string res = ""; //定义返回值
stack<string> stk;
for(int i = 0;i < items.size();i++) {
if(check_true(items[i])) stk.push(items[i]);
else if(check_back(items[i]) && !stk.empty()) stk.pop();
}
if(stk.empty()) res += "/";
while(!stk.empty()) {
res.insert(0, stk.top());
res.insert(0, "/");
stk.pop();
}
return res;
}
//检查是不是有效返回
bool check_back(const string s) {
if(s == "..") return true;
return false;
}
bool check_true(const string s) {
if(s != "." && s != ".." && s != "") return true;
return false;
}
//字符串分割
vector<string> split(const string s, char t) {
vector<string> items;
for(int i = 0;i < s.size();i++) {
int j = i;
string item;
while(j < s.size() && s[j] != t) item += s[j++];
i = j;
items.push_back(item);
}
return items;
}
};