Simplify Path

来源:互联网 发布:基金买卖模拟软件 编辑:程序博客网 时间:2024/06/10 17:58

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:

class Solution {public:    string simplifyPath(string path) {        stack<char> s;        s.push('/');        string str = "";        for(int i = 1; i <= path.length(); ++i)        {            if(i < path.length() && path[i] != '/') str += path[i];            else            {                if(str == "" || str == ".") ;                else if(str == "..")                {                    if(s.size() > 1)                    {                        s.pop();                        while(s.top() != '/') s.pop();                    }                }                else                {                    for(int j = 0; j < str.length(); ++j) s.push(str[j]);                    s.push('/');                }                str = "";            }        }        string res = "";        while(!s.empty())        {            res += s.top();            s.pop();        }        reverse(res.begin(), res.end());        if(res.length() > 1) res.erase(res.end()-1);        return res;    }};


0 0
原创粉丝点击