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;
}
本文介绍了一种简化Unix风格文件路径的方法,通过使用C++中的vector来模拟栈操作,实现了对路径中'.'和'..'的有效处理。
6861

被折叠的 条评论
为什么被折叠?



