思路:参考网上的讨论,用'/'作为分隔符,得到一系列子字符串 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.csdn.net/maverick1990/article/details/23275051