Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
思路:字符串的处理,依然考虑双指针,
用vector实现栈的功能:
遇到.不变;
遇到..如果vector不为空,则弹出最后一个,
其他,压入vecort;
代码:
string simplifyPath(string path) {
vector<string> tempVector;
string res;
int len=path.length();
int i=0;
string temp="";
int start=0;
int end=0;
while(start < len)
{
end=start;
while(end<len && path[end]!='/')
{
end++;
}
temp=path.substr(start,end-start);
if(temp==".."&&!tempVector.empty())
tempVector.pop_back();
else if(temp!="" && temp!="."&&temp!="..")
tempVector.push_back(temp);
start=end+1;
}
if(tempVector.size() == 0)
{
res="/";
return res;
}
int j=0;
int count=tempVector.size();
while(j<count)
{
res=res+"/";
res=res+tempVector[j];
++j;
}
return res;
}