[解题思路] 利用栈的特性,如果substring element 1. 等于“/”,跳过,直接开始寻找下一个element 2. 等于“.”,什么都不需要干,直接开始寻找下一个element 3. 等于“..”,弹出栈顶元素,寻找下一个element 4. 等于其他,插入当前elemnt为新的栈顶,寻找下一个element 最后,再根据栈的内容,重新拼path。这样可以避免处理连续多个“/”的问题。
string simplifyPath(string path) {
vector<string> stack;
assert(path[0]=='/');
int i=0;
while(i< path.size())
{
while(path[i] =='/' && i< path.size()) i++; //skip the begining '////'
if(i == path.size())
break;
int start = i;
while(path[i]!='/' && i< path.size()) i++; //decide the end boundary
int end = i-1;
string element = path.substr(start, end-start+1);
if(element == "..")
{
if(stack.size() >0)
stack.pop_back();
}
else if(element!=".")
stack.push_back(element);
}
if(stack.size() ==0) return "/";
string simpPath;
for(int i =0; i<stack.size(); i++)
simpPath += "/" + stack[i];
return simpPath;
}
//another one
- traverse the string to record each folder name.
- two special cases:
b.single dot: do nothing (don't push it).
string simplifyPath(string path) {
vector<string> nameVect;
string name;
path.push_back('/');
for(int i=0;i<path.size();i++){
if(path[i]=='/'){
if(name.size()==0)continue;
if(name==".."){ //special case 1:double dot,pop dir
if(nameVect.size()>0)nameVect.pop_back();
}else if(name=="."){//special case 2:singel dot,don`t push
}else{
nameVect.push_back(name);
}
name.clear();
}else{
name.push_back(path[i]);//record the name
}
}
string result;
if(nameVect.empty())return "/";
for(int i=0;i<nameVect.size();i++){
result.append("/"+nameVect[i]);
}
return result;
}
No comments:
Post a Comment