Leetcode 71. Simplify Path

来源:互联网 发布:崩坏3rd淘宝代充 编辑:程序博客网 时间:2024/05/18 01:55

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) {        if (path[0] != '/')            return string();        size_t n = path.size();        string ret;        size_t i =  0;        while (i < n) {            if (path[i] == '/') {                ++i;                while (i != n && path[i] == '/')                    ++i;                if (i == n) break;                string tmp;                while (i != n && path[i] != '/') {                    tmp += path[i];                    ++i;                }                if (tmp == ".."){                    int j = ret.size() - 1;                    while(ret[j] != '/')                        --j;                    if (j < 0) j = 0;                    ret.erase(ret.begin() + j, ret.end());                }                 else if (tmp != ".")                        ret += ('/' + tmp);            }        }        if (ret.size() == 0) return string(1, '/');        if (ret[0] = '/')            return ret;        else             return '/' + ret;    }};

参考后

class Solution {public:    string simplifyPath(string path) {        stringstream ss(path);        string tmp;        string ret;        vector<string> v;        while(getline(ss, tmp, '/')) {            if (tmp == "" || tmp == ".") continue;            if (tmp == "..") {                if (!v.empty()) v.pop_back();                continue;            }            v.push_back(tmp);        }        if (v.empty()) return string(1, '/');        for (auto str : v) {            ret += ('/' + str);        }        return ret;    }};
原创粉丝点击