题目要求:
路径简化
Example:
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
path = "/a/../../b/../c//.//", => "/c"
path = "/a//b////c/d//././/..", => "/a/b/c"
最主要的是边界情况的处理:
处理思路:
利用vector存储每个有效路径单元如"/var/log/exm/"->/var /log /exm,遍历路径,存储依次存储,遇上'//' '/.'等直接忽略,'/..'则删除vector末尾的路径。
边界情况:
最后一个字符是否是'/'
以及vector为空时,遇到/..如何处理
源码如下:
class Solution {
public:
string simplifyPath(string path) {
vector<string> word;
int pre = 0;
int pos = 0;
string ans;
for (int index=1;index<path.size();++index){
if (path[index] != '/' && index < path.size()-1)continue;
pos = index;
string substring;
/*
*处理最后一个字符是否为'/'额边界情况
*/
if (index == path.size()-1 && path[index]!='/')
substring = path.substr(pre,pos-pre+1);
else{
substring = path.substr(pre,pos-pre);
}
if (substring == "/.."){
//处理vector为空的情况
if (!word.empty())
word.pop_back();
pre = pos;
continue;
}
if (substring != "/" && substring != "/."){
word.push_back(substring);
}
pre = pos;
}
if (word.empty()){
return "/";
}
for (int index=0;index<word.size();index++){
ans = ans+word[index];
}
return ans;
}
};