您的位置:首页 > 其它

Simplify Path

2015-12-11 20:02 435 查看
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,
2.遇到../,当前位置-3,然后回退到上一个斜杠处
测试用例:
.
..
/.
/..
/...
/./
/../
///
/./
/../
/.../
/..../../../../../../
/a../././../
/a.../././..
*/
class Solution {
public:
string simplifyPath(string path) {
int i=0,j=0;
if(path.size()>0){
path.push_back('/');
}
string res(path.size(),' ');
while(i<path.size()){
if(i>0 && path[i]==res[j-1] && path[i]=='/') {
i++;
continue;
}
res[j++] = path[i];
if(path[i]=='/'){
int pre_level_start = i-3>=0? i-3:0;
if(path.substr(pre_level_start,i-pre_level_start+1)=="/../"){
j-=4;
while(j-1>=0 && res[j-1]!='/') --j;
if(j==0){
j=1;
}
}else{
pre_level_start = i-2>=0? i-2:0;
if(path.substr(pre_level_start,i-pre_level_start+1)=="/./"){
j-=2;
}
}
}
i++;
}
if(j>1 && res[j-1]=='/') --j;
res.erase(res.begin()+j,res.end());
return res;
}
};


Next challenges: (H) Largest Rectangle in Histogram (E) Min Stack (M) Reverse Words in a String II
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: