Simplify Path
Given an absolute path for a file (Unix-style), simplify it.
For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”
class Solution {
public:
string simplifyPath(string path) {
if(path.size()==0)
return "";
stack<string> temp;
string str;
for(int i=0;i<path.size();i++){
string str;
while(i<path.size()&&path[i]=='/') //跳过所有的'/'
i++;
while(i<path.size()&&path[i]!='/'){
str.push_back(path[i]);
i++;
}
if(str==".."&&!temp.empty()){ //如果是..需要从栈里pop一个字符串
temp.pop();
}
if(str!=""&&str!="."&&str!=".."){
temp.push(str);
}
str.clear();
}
if(temp.empty())
return "/";
while(!temp.empty()){
str='/'+temp.top()+str;
temp.pop();
}
return str;
}
};