Leetcode NO.71 Simplify Path

来源:互联网 发布:无印良品水乳 知乎 编辑:程序博客网 时间:2024/06/05 18:22

本题题目于要求如下:

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".
本题的难度并不高,对我来说,难度主要集中在unix-style command的含义。。后来搞明白了:

  1. "."的意思是忽略,不做任何处理。
  2. ".."的意思是返回上一级,具体在本题的stack的操作是,pop栈顶的元素,由于栈顶的下一层即为上一级的路径。。
知道了这两点后,剩下的就很简单了。用stringstream类,将字符串根据'/'进行分割即可。。

具体代码如下:

class Solution {public:    string simplifyPath(string path) {        stack<string> res_stack;        string res = "";        string token;        istringstream is(path);        while (getline(is, token, '/')) {        if (token == "." or token == "") {        continue;        }        else if (token == ".." and !res_stack.empty()) {        res_stack.pop();        }        else if (token != "..") {        res_stack.push(token);        }        }        while (!res_stack.empty()) {        res = "/" + res_stack.top() + res;        res_stack.pop();        }        if (res == "") {        res = "/";        }        return res;    }};


0 0
原创粉丝点击