zoukankan      html  css  js  c++  java
  • [LintCode] Simplify Path 简化路径

    Given an absolute path for a file (Unix-style), simplify it.

     
    Example

    "/home/", => "/home"

    "/a/./b/../../c/", => "/c"

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

    LeetCode上的原题,请参见我之前的博客Simplify Path

    解法一:

    class Solution {
    public:
        /**
         * @param path the original path
         * @return the simplified path
         */
        string simplifyPath(string& path) {
            int left = 0, right = 0, n = path.size();
            stack<string> s;
            string res = "";
            while (right < n) {
                while (left < n && path[left] == '/') ++left;
                right = left;
                while (right < n && path[right] != '/') ++right;
                string t = path.substr(left, right - left);
                if (t == "..") {
                    if (!s.empty()) s.pop();
                } else if (t != ".") {
                    if (!t.empty()) s.push(t);
                }
                left = right;
            }
            while (!s.empty()) {
                res = "/" + s.top() + res; s.pop();
            }
            return res.empty() ? "/" : res;
        }
    };

    解法二:

    class Solution {
    public:
        /**
         * @param path the original path
         * @return the simplified path
         */
        string simplifyPath(string& path) {
            string res, t;
            stringstream ss(path);
            vector<string> v;
            while (getline(ss, t, '/')) {
                if (t == "" || t == ".") continue;
                if (t == ".." && !v.empty()) v.pop_back();
                else if (t != "..") v.push_back(t);
            }
            for (string s : v) res += "/" + s;
            return res.empty() ? "/" : res;
        }
    };
  • 相关阅读:
    Net学习日记_SQL_1
    Net学习日记_基础提高_11_俄罗斯方块_代码篇
    Net学习日记_基础提高_11_俄罗斯方块_整理概括篇
    Net学习日记_基础提高_10
    C#抽象类和接口
    RSS大全
    如何使用deparam.js抓参数
    h5页面解决软键盘与100%X100%的页面的冲突
    29、数据库三大范式精要总结
    28、数据库三大范式精讲
  • 原文地址:https://www.cnblogs.com/grandyang/p/5716789.html
Copyright © 2011-2022 走看看