美文网首页
71.简化路径

71.简化路径

作者: HITZGD | 来源:发表于2018-11-18 10:17 被阅读0次

    题目
    给定一个文档 (Unix-style) 的完全路径,请进行路径简化。

    例如:
    path = "/home/", => "/home"
    path = "/a/./b/../../c/", => "/c"

    边界情况:

    你是否考虑了 路径 = "/../" 的情况?
    在这种情况下,你需返回 "/" 。
    此外,路径中也可能包含多个斜杠 '/' ,如 "/home//foo/" 。
    在这种情况下,你可忽略多余的斜杠,返回 "/home/foo" 。

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

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

    C++中split的用法

    string temp;
    stringstream stringPath(path);
    getline(stringPath, temp, '/')
    
    #include <iostream>
    #include <sstream>
    #include <vector>
    using namespace std;
    class Solution {
    public:
        string simplifyPath(string path) {
            string result, temp;
            stringstream stringPath(path);
            vector<string> v;
            while (getline(stringPath, temp, '/'))
            {
                if (temp =="" || temp == ".") continue;
                if (temp == ".." && !v.empty()) v.pop_back();
                else if (temp != "..") v.push_back(temp);
            }
            for (auto eve : v) result += "/" + eve;
            return result.empty() ? "/" : result;
        }
    };
    
    int main(int argc, char* argv[])
    {
        string path = "/a/./b/../../c/";
        auto res = Solution().simplifyPath(path);
        return 0;
    }
    
    

    相关文章

      网友评论

          本文标题:71.简化路径

          本文链接:https://www.haomeiwen.com/subject/oqgwfqtx.html