# 71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

Corner Cases:

• Did you consider the case where path = "/../"?
In this case, you should return "/".
• Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
In this case, you should ignore redundant slashes and return "/home/foo".

class Solution {
public:
string simplifyPath(string path) {
stack<string> mystack;

int p = 0;
while (path[p] == '/'){
p++;
}
if (p == path.size())
return "/";
path = path.substr(p);

string s = spilt(path, '/');
while (!s.empty()){
if (s.compare(".") == 0){
//do nothing

}
else if (s.compare("..") == 0){
if (!mystack.empty())
mystack.pop();
}
else
mystack.push(s);

int p = 0;
while (path[p] == '/'){
p++;
}
path = path.substr(p);
s = spilt(path, '/');
}
if (mystack.empty()){
return "/";
}
vector<string> simp(mystack.size());
for (int i = 0; i < simp.size(); i++){
simp[i] = mystack.top();
mystack.pop();
}
string res;
for (int i = simp.size()-1; i >= 0; i--){
res += "/" + simp[i];
}
return res;
}
string spilt(string& path, char ch){
string s;
int i;
int size = path.size();
for (i = 0; i < path.size(); i++){
char c = path[i];
if (c == ch){
s = path.substr(0, i);
path = path.substr(i + 1);
break;
}
}
if (i == size){
s = path;
path.clear();
}
return s;
}
};


• 本文已收录于以下专栏：

举报原因： 您举报文章：71. Simplify Path 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)