leetcode-Simplify Path

来源:互联网 发布:美少女万华镜 mac 编辑:程序博客网 时间:2024/05/17 08:49

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;
    }


0 0