首页 > 技术文章 > 【LeetCode】71. Simplify Path

ganganloveu 2014-06-11 20:57 原文

Simplify Path

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函数

以及用进出栈来保存最简路径。

path:"/a/./b/../../c/"

split:"a",".","b","..","..","c"

stack:push(a), push(b), pop(b), pop(a), push(c) --> c

 

注意:string(it1, it2)的用法

string  (InputIterator first, InputIterator last);
Copies the sequence of characters in the range [first,last), in the same order.

 

class Solution {
public:
    static bool isSlash(char c)
    {
        return (c == '/');
    }
    static bool notSlash(char c)
    {
        return !isSlash(c);
    }
    vector<string> split(string str)
    {
        vector<string> ret;
        string::iterator it = str.begin();
        while(it != str.end())
        {
            it = find_if(it, str.end(), notSlash);
            string::iterator it2 = find_if(it, str.end(), isSlash);
            if(it != str.end())
                ret.push_back(string(it, it2));
            it = it2;
        }
        return ret;
    }
    string simplifyPath(string path) {
        vector<string> v = split(path);
        stack<string> stk;
        string ret = "";
        for(int i = 0; i < v.size(); i ++)
        {
            if(v[i] == ".")
                ;
            else if(v[i] == "..")
            {
                if(!stk.empty())
                    stk.pop();
            }
            else
                stk.push(v[i]);
        }
        while(!stk.empty())
        {
            ret = "/" + stk.top() + ret;
            stk.pop();
        }
        if(ret == "")
            return "/";
        return ret;
    }
};

推荐阅读