Given an absolute path for a file (Unix-style), simplify it.
For example,
path = "/home/"
, => "/home"
path = "/a/./b/../../c/"
, => "/c"
click to show corner cases.
Corner Cases:
- Did you consider the case where path =
"/../"
?
In this case, you should return"/"
. - Another corner case is the path might contain multiple slashes
'/'
together, such as"/home//foo/"
.
In this case, you should ignore redundant slashes and return"/home/foo"
.
==================
简化路径,
注意:1,能够自动优化路径例如,/../可以变为/
2,能够将 多了斜杠/// 简化为一个/
=================
思路:
这里需要一个字符串划分函数,c++中是没有提供字符串划分函数的.
可以参考[ http://www.cnblogs.com/li-daphne/p/5524752.html ]分析过程.
主要是利用了string类中的find,substr函数
----
对输入字符串做slipt之后,所有的路径名字包括[.]和[..]都会存入一个vector中,
此后,我们再利用栈来剔除[.]和[..]路径,
最后一次对栈中的数据进行处理就好了.
============
代码如下:
void myslipt(string &s,vector<string> &re,string &c){
std::string::size_type pos1,pos2;
pos2 = s.find(c);///find
pos1 = ;
while(std::string::npos != pos2){
string t = s.substr(pos1,pos2-pos1);///[p1,p2)
if(!t.empty()){
re.push_back(t);
}
pos1 = pos2+c.size();
pos2 = s.find(c,pos1);
}
if(pos1!=s.length()){
re.push_back(s.substr(pos1));
}
} string simplifyPath(string path) {
vector<string> re;
string c = "/";
myslipt(path,re,c);
stack<string> st;
for(size_t i = ;i<re.size();i++){
if(re[i]==".") continue;
else if(re[i]==".."){
if(st.empty()){
continue;
}else{
st.pop();
}///if-else
}else{
st.push(re[i]);
}
}
string result;
while(!st.empty()){
result.insert(,st.top());
result.insert(,"/");
st.pop();
}
return result;
}