返回给定绝对路径的,简化绝对路径

来源:互联网 发布:怎么样宣传淘宝店铺 编辑:程序博客网 时间:2024/05/17 22:47

本题源自LeetCode

-----------------------------------------------------

例如:

path ="/home/", =>"/home"
path ="/a/./b/../../c/", =>"/c"

思路1:

将绝对路径按 / 划分为单个元素。然后判断如果 分割的元素为 '. ’ '则跳过,如果遇见 '..' 则弹出上一个元素。否则入栈

代码:

    string simplifyPath(string path) {        int len=path.length();        stringstream ss(path);        string sub;        vector<string> res;        while(getline(ss,sub,'/')){            if(sub==""||sub==".")                continue;            else if(sub==".."&&!res.empty()){                res.pop_back();            }else if(sub!=".."){                res.push_back(sub);            }        }        string result;        for(auto tmp:res){            result+='/'+tmp;        }        return res.empty()?"/":result;                   }

思路 2  

如果遇见‘/’或‘.’则跳过,遇见‘..’则弹出元素。否则压栈。

string simplifyPath(string path) {        int len=path.length();        vector<string> res;        for(int i=0;i<len;i++){            while(i<len&&path[i]=='/'){                i++;            }            if(i==len)                break;            string tmp;            while(i<len&&path[i]!='/'){                tmp+=path[i++];            }            if(tmp==".")                continue;            else if(tmp==".."&&res.size())                res.pop_back();            else if(tmp!="..")                res.push_back(tmp);        }        string result;        for(auto tmp:res){            result+='/'+tmp;        }        if(result=="")            result="/";        return result;    }


原创粉丝点击