LeetCode-Simplify Path

来源:互联网 发布:matlab合并三个矩阵 编辑:程序博客网 时间:2024/05/16 10:54

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".
Solution:

Code:

<span style="font-size:14px;">class Solution {public:    string simplifyPath(string path) {        path += "/";        int length = path.size();        stack<string> stk;        string name;        for (int i = 0; i < length; i++) {            if (path[i] == '/') {                if (name == "." || name == "") {                } else if (name == "..") {                    if (!stk.empty()) stk.pop();                } else stk.push(name);                name = "";            } else                name += path[i];        }        string result;        while (!stk.empty()) {            result = "/" + stk.top() + result;            stk.pop();        }        if (result == "") return "/";        return result;    }};</span>



0 0
原创粉丝点击