zoukankan      html  css  js  c++  java
  • 【Leetcode】【Medium】Simplify Path

    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路径,即省略多余字符“/”和运算“.”、"..",返回unix的真实路径;

    需要考虑的特殊情况是:

    1、根目录下操作"..",还是根目录

    2、连续两个“/”,可看做无任何作用

    3、路径末尾的"/",要消除

    思路:

    每次取出两个“/”之间的字符,如果是"."或者空字符表示还在本层路径,如果是".."表示返回上一层路径,如果是其他字符,则表示下一层路径名;

    用栈来保存每一层路径非常合适,但是后来变成过程中,使用vector来模拟栈操作,在最后整合最终路径时反而更方便。

    代码:

     1 class Solution {
     2 public:
     3     string simplifyPath(string path) {
     4         string res, substr;
     5         vector<string> stk;
     6         stringstream ss(path);
     7         
     8         while(getline(ss, substr, '/')) {
     9             if (substr == ".." and !stk.empty()) 
    10                 stk.pop_back();
    11             else if (substr != ".." && substr != "." && substr != "") 
    12                 stk.push_back('/' + substr);
    13         }
    14         
    15         for (int i = 0; i < stk.size(); ++i)
    16             res += stk[i];
    17         
    18         return res.empty() ? "/" : res;
    19     }
    20 };
  • 相关阅读:
    JSONRPC(jsonrpc4j)使用demo
    Java游戏服务器成长之路——感悟篇
    使用Echarts进行可视化的数据线呈现
    vb 获取本机MAC地址
    mysql的索引使用不当速度比没加索引还慢
    创业名言
    网络公司的转变
    用php来读取团购网站的api
    php中全局变量global的使用
    MongoDB被全球最大的分类信息网站Craigslist使用
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4599349.html
Copyright © 2011-2022 走看看