码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Simplify Path

时间:2014-06-12 07:51:29      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   java   http   

Simplify Path

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

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

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

click to show corner cases.

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".

 

核心在于编写一个split函数以及用进出栈来保存最简路径。

bubuko.com,布布扣
class Solution 
{
public:
    // true if the argument is slash, false otherwise
    static bool is_slash(char c)
    {
        return (c==/);
    }

    // false if the argument is slash, true otherwise
    static bool not_slash(char c)
    {
        return !is_slash(c);
    }

    vector<string> split(const string& str)
    {
        typedef string::const_iterator iter;
        vector<string> ret;

        iter i = str.begin();
        while (i != str.end()) {

            // ignore leading slashes
            i = find_if(i, str.end(), not_slash);

            // find end of next word
            iter j = find_if(i, str.end(), is_slash);

            // copy the characters in [i, j)
            if (i != str.end())
                ret.push_back(string(i, j));
            i = j;
        }
        return ret;
    }

    string simplifyPath(string path) 
    {
        stack<string> pstack;
        vector<string> pv = split(path);
        for(vector<string>::size_type st = 0; st < pv.size(); st ++)
        {
            if(pv[st] == "..")
            {
                if(!pstack.empty())
                    pstack.pop();
            }
            else if(pv[st] != ".")
                pstack.push(pv[st]);
        }

        string output = "";
        if(pstack.empty())
        {
            output = "/";
            return output;
        }
        while(!pstack.empty())
        {
            output = "/" + pstack.top() + output;
            pstack.pop();
        }
        return output;
    }
};
bubuko.com,布布扣

bubuko.com,布布扣

 

【LeetCode】Simplify Path,布布扣,bubuko.com

【LeetCode】Simplify Path

标签:style   class   blog   code   java   http   

原文地址:http://www.cnblogs.com/ganganloveu/p/3782727.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!