simplify path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"

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

本题简单来说 就是字符串的处理 同时要有相关的情况分类 比如当前目录 父目录 多个斜线等

但其实 就父目录时需要回到上一路经 当前目录时不做任何变化 其他目录时需要进入其他目录 这一特征  本题可用栈来存储整个路径寻找的过程

在path中 逐一找到斜线之间的当前路径名 并分类判断 分类处理  使得栈中存储的为路径的一系列名字  最后再反向串起来成路径真正的字符串即可。

   string simplifyPath(string path) {
        string res_path="";
        if (path.size()==0)
            return res_path;
        stack<string> stack_path;
        for (int i=0; i<path.size();)
        {
            while(i<path.size() && path[i]=='/')
                ++i;
            string name="";
            while(i<path.size() && path[i]!='/')
                name += path[i++];
            if (name==".." && !stack_path.empty())
                stack_path.pop();
            else if(name!="" && name!="." && name!="..")
                stack_path.push(name);
        }
        if (stack_path.empty())
            res_path += '/';
        else
        {
            while(!stack_path.empty())
            {
                res_path = '/'+stack_path.top()+res_path;
                stack_path.pop();
            }
        }
        return res_path;
    }

 

posted @ 2017-02-16 16:35  糯米米一粒  阅读(190)  评论(0编辑  收藏  举报