您的位置:首页 > 其它

LeetCode---Simplify Path

2015-11-14 17:15 387 查看
题目大意:给出一个UNIX-style的路径,将其进行简化,如果遇见“/.”则保持当前路径 ,如果遇见“/..”则返回上一层路径,最后输出简化后的路径。

算法思想:

1.将给出的路径进行分割将每一层路径存储在容器中。

2.按照简化规则进行路径简化,遍历容器如果遇见“.”则continue,如果遇见“..”则进行出栈操作(栈不空),如果是其他字符串则入栈。

3.将栈中存储的简化后的路径单元拼接起来。

4.返回简化后的路径。

代码如下:

class Solution {
public:
string simplifyPath(string path) {
if(path.size()<=1) return "/";
vector<string> str;
stack<string> str_pat;
string temp="",res="";
for(char c:path){
if(c!='/')
temp+=c;
else{
if(temp.size()!=0){
str.push_back(temp);
temp="";
}
}
}
if(temp.size()!=0)
str.push_back(temp);

for(string s:str){
if(s=="."){
continue;
}
else if(s==".."){
if(!str_pat.empty())
str_pat.pop();
}
else{
str_pat.push(s);
}
}
while(!str_pat.empty()){
temp="/"+str_pat.top()+res;
str_pat.pop();
res=temp;
temp="";
}
if(res.size()==0)
res="/";
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: