[LintCode] Simplify Path 简化路径

 

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

 
Example

"/home/", => "/home"

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

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

 

LeetCode上的原题,请参见我之前的博客Simplify Path

 

解法一:

class Solution {
public:
    /**
     * @param path the original path
     * @return the simplified path
     */
    string simplifyPath(string& path) {
        int left = 0, right = 0, n = path.size();
        stack<string> s;
        string res = "";
        while (right < n) {
            while (left < n && path[left] == '/') ++left;
            right = left;
            while (right < n && path[right] != '/') ++right;
            string t = path.substr(left, right - left);
            if (t == "..") {
                if (!s.empty()) s.pop();
            } else if (t != ".") {
                if (!t.empty()) s.push(t);
            }
            left = right;
        }
        while (!s.empty()) {
            res = "/" + s.top() + res; s.pop();
        }
        return res.empty() ? "/" : res;
    }
};

 

解法二:

class Solution {
public:
    /**
     * @param path the original path
     * @return the simplified path
     */
    string simplifyPath(string& path) {
        string res, t;
        stringstream ss(path);
        vector<string> v;
        while (getline(ss, t, '/')) {
            if (t == "" || t == ".") continue;
            if (t == ".." && !v.empty()) v.pop_back();
            else if (t != "..") v.push_back(t);
        }
        for (string s : v) res += "/" + s;
        return res.empty() ? "/" : res;
    }
};

 

posted @ 2016-07-28 23:54  Grandyang  阅读(703)  评论(0编辑  收藏  举报
Fork me on GitHub