题目:
解答:
很合理的想法,是用一个栈来记录整个path路径的每个节点,如果遇到"…“就回退一个位置,遇到”."就忽略,退到空栈了就不处理。
但是后来发现用栈的话,最后取出数据麻烦,所以还是使用了一个vector来记录所有的path路径节点。
代码:
class Solution {
public:
string simplifyPath(string path) {
vector<string> vec(1000);
int len = path.size();
int index = 0;
for(int i = 0;i < len; ){
int k = i;
while(k < len && path[k] == '/') ++k;
if(k == len) break;
int end = k;
while(end < len && path[end] != '/') ++end;
string tmp = path.substr(k, end - k);
//cout << tmp << endl;
i = end;
if(tmp == ".")
continue;
if(tmp == ".."){
if(index > 0)
index--;
continue;
}
vec[index++] = tmp;
}
if(index == 0)
return "/";
stringstream ss;
for(int i = 0;i < index; ++i){
ss << "/" << vec[i];
}
return ss.str();
}
};
更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)