首页 > 其他 > 详细

71. Simplify Path

时间:2016-03-14 00:09:43      阅读:187      评论:0      收藏:0      [点我收藏+]

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

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

Corner Cases:

 

  • Did you consider the case where path = "/../"?
    In this case, you should return "/".
  • Another corner case is the path might contain multiple slashes ‘/‘ together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".
class Solution {
public:
    string simplifyPath(string path) {
        int l = path.size(), i, j;
        i = 0;
        string s;
        vector<string> v;
        while(i >= 0 && i < l)
        {
            while(path[i] == /)
                i++;
            if(i >= l)
                break;
            j = path.find("/", i);
            if(-1 == j)
                s = path.substr(i);
            else
                s = path.substr(i, j-i);
            if(s == "..")
            {
                if(v.size())
                    v.erase(v.end()-1);
            }
            else if(s != ".")
                v.insert(v.end(), s);
            i = j;
        }
        if(!v.size())
            return "/";
        s = "";
        for(i=0; i<v.size(); i++)
        {
            s += "/";
            s += v[i];
        }
        return s;
    }
};

 

测试用例:

"/." -- "/"

"/../" -- "/"

"/home/" -- "/home"

"/a/./b/../../c/" -- "/c"

71. Simplify Path

原文:http://www.cnblogs.com/argenbarbie/p/5274198.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!