• 【LeetCode】71. Simplify Path


    Simplify Path

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

    核心在于编写一个以'/'为分隔符的split函数

    以及用进出栈来保存最简路径。

    path:"/a/./b/../../c/"

    split:"a",".","b","..","..","c"

    stack:push(a), push(b), pop(b), pop(a), push(c) --> c

    注意:string(it1, it2)的用法

    string  (InputIterator first, InputIterator last);
    Copies the sequence of characters in the range [first,last), in the same order.
    class Solution {
    public:
        static bool isSlash(char c)
        {
            return (c == '/');
        }
        static bool notSlash(char c)
        {
            return !isSlash(c);
        }
        vector<string> split(string str)
        {
            vector<string> ret;
            string::iterator it = str.begin();
            while(it != str.end())
            {
                it = find_if(it, str.end(), notSlash);
                string::iterator it2 = find_if(it, str.end(), isSlash);
                if(it != str.end())
                    ret.push_back(string(it, it2));
                it = it2;
            }
            return ret;
        }
        string simplifyPath(string path) {
            vector<string> v = split(path);
            stack<string> stk;
            string ret = "";
            for(int i = 0; i < v.size(); i ++)
            {
                if(v[i] == ".")
                    ;
                else if(v[i] == "..")
                {
                    if(!stk.empty())
                        stk.pop();
                }
                else
                    stk.push(v[i]);
            }
            while(!stk.empty())
            {
                ret = "/" + stk.top() + ret;
                stk.pop();
            }
            if(ret == "")
                return "/";
            return ret;
        }
    };

  • 相关阅读:
    ORACLE B-TREE(B树)索引
    安装CentOS 6.4 64 位操作系统
    环境搭建(一)——linux 安装tomcat
    Linux基础
    sql必知必会
    Mysql基础
    shell编程基础
    Allpairs 正交分析工具的使用(测试用例设计)
    Sublime Text3配置SublimeREPL快捷键的方法(Python)
    XSS攻击及预防
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/3782727.html
Copyright © 2020-2023  润新知