首页 > 代码库 > 【LeetCode】Simplify Path

【LeetCode】Simplify Path

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函数以及用进出栈来保存最简路径。

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;
    }
};