LeetCode---Simplify Path

来源:互联网 发布:全球经济数据时时播报 编辑:程序博客网 时间:2024/05/28 15:07

题目大意:给出一个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;    }};


0 0
原创粉丝点击