Simplify Path

来源:互联网 发布:java volatile用法 编辑:程序博客网 时间:2024/06/07 09:55

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风格下的文件的绝对路径。

字符串处理,由于”..”是返回上级目录(如果是根目录则不处理),因此可以考虑用栈记录路径名,以便于处理。需要注意几个细节:
使用一个vector来维护。

重复连续出现的’/’,只按1个处理,即跳过重复连续出现的’/’;
如果路径名是”.”,则不处理;
如果路径名是”..”,则需要删除,如果栈为空,则不做处理;
如果路径名为其他字符串,加入vector。

class Solution {public:    string simplifyPath(string path) {        vector<string> str;        string tmp = "";        for (int i = 0; i < path.size(); i++)        {            while(path[i] == '/' &&i < path.size())                i++;            string tmp = "";            while(path[i] != '/' && i < path.size()){                tmp += path[i];                i++;            }            if(tmp == ".." && !str.empty())                str.pop_back();            else if(tmp != ".." && tmp != "/" && tmp != "."&& tmp!="")                str.push_back(tmp);        }        if(str.empty())            return "";        string res = "";        for (int i = 0; i < str.size(); i++)        {            res = res + "/" +str[i];        }        return res;    }};
0 0
原创粉丝点击