2018秋招 搜狐 简化路径

来源:互联网 发布:微信配图软件 编辑:程序博客网 时间:2024/05/17 00:57

这题是leetcode原题

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

For example,
path = “/home/”, => “/home”
path = “/a/./b/../../c/”, => “/c”

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”.

AC代码:

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