leetcode---simplify-path---字符串

来源:互联网 发布:对付淘宝无良卖家 编辑:程序博客网 时间:2024/05/23 02:17

题目描述
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)     {        vector<string> ans;        stringstream sin(path);        string tmp;        while(getline(sin, tmp, '/'))        {            if(tmp == "" || tmp == ".")                continue;            else if(tmp == ".." && !ans.empty())                ans.pop_back();            else if(tmp != "..")                ans.push_back(tmp);        }        string s = "";        for(string st : ans)            s += "/" + st;        return s == "" ? "/" : s;    }};
原创粉丝点击