Leetcode: Simplify Path

来源:互联网 发布:alpha1机器人软件下载 编辑:程序博客网 时间:2024/06/06 13:24

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".
不难,就是需要处理各种边界条件。
class Solution {public:    string simplifyPath(string path) {        string result;        if (path.empty()) {            return result;        }                stack<string> paths;        string tmp;        size_t cur_pos = 0;        size_t prev_pos = string::npos;        path.push_back('/');        for (int cur_pos = 0; cur_pos < path.size(); ++cur_pos) {            if (path[cur_pos] == '/') {                if (prev_pos != string::npos) {                    tmp = path.substr(prev_pos + 1, cur_pos - prev_pos - 1);                    if (!tmp.empty()) {                        if (tmp == "..") {                            if (!paths.empty()) {                                paths.pop();                            }                        }                        else if (tmp != ".") {                            paths.push(tmp);                        }                    }                }                prev_pos = cur_pos;            }                    }                while (!paths.empty()) {            result = "/" + paths.top() + result;            paths.pop();        }                if (result.empty()) {            result = "/";        }                return result;    }};
===============第二次===============
class Solution {public:    string simplifyPath(string path) {        if (path.empty()) {            return path;        }                stack<string> paths;        int start = 0;        path += "/";        for (int i = 0; i < path.size(); ++i) {            if (path[i] == '/') {                string tmp = path.substr(start, i - start);                if (tmp == "..") {                    if (!paths.empty()) {                        paths.pop();                    }                }                else if (!tmp.empty() && tmp != "."){                    paths.push(tmp);                }                start = i + 1;            }        }                string result;        if (paths.empty()) {            result = "/";        }        else {            while (!paths.empty()) {                result = "/" + paths.top() + result;                paths.pop();            }        }                return result;    }};


0 0
原创粉丝点击