简化路径

问题:简化路径

 

class Solution {
public:
    string simplifyPath(string path) {
        vector<string>realpath;
        string token;
        istringstream tokenStream(path);
        vector<string> tokens;

        while(getline(tokenStream,token,'/'))
        {
            if (token=="") continue;
            tokens.push_back(token);
        }
        for (int i=0;i<tokens.size();i++)
        {
            string token = tokens[i];
            if(token == ".")
            {
                continue;
            }
            else if(token == "..")
            {
                if(realpath.size()>0)
                    realpath.pop_back();
            }
            else
            {
                realpath.push_back(token);
            }
        }
        string ans = "";
        for (auto item:realpath)
        {
            ans.push_back('/');
            ans+=item;
        }
        return ans == "" ? "/" : ans;
    }
};

 

posted @ 2020-07-26 14:19  r1-12king  阅读(127)  评论(0编辑  收藏  举报