zoukankan      html  css  js  c++  java
  • [LeetCode] 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".

    如果仅仅从不断replace输入路径的角度出发,会非常复杂。

    如果用一个栈来一次存储各级路径的directory名字,然后重组,会简便一些,这也是文件路径简化类题目的常用思路。

    为了末尾可以顺序遍历栈重组path,我们不用传统的stack lib,而用vector来实现栈,这样可以方便顺序遍历。

    代码:

    class Solution {
    public:
        string simplifyPath(string path) {
            if(path.length() == 0) return "";
            vector<string> v;
            int p = 0, start = 0;
            while(p < path.length()){
                if(path[p] == '/') ++p;
                else{
                    start = p;
                    while(p < path.length() && path[p] != '/') ++p;
                    string temp = path.substr(start, p-start);
                    if(temp == ".."){ 
                        if(!v.empty()) v.pop_back(); //遇到".."就出栈
                        else{
                            if(path[0] != '/') v.push_back(temp); //如果没东西可以出,就要看path是否以根目录开头了,不是以根目录开头的话,".."要进栈的
                        }
                    }else if(temp == "."){} //遇到"."就跳过
                    else if(temp.length() > 0){
                        v.push_back(temp);
                    }
                }
            }
            string res = (path[0] == '/' ? "/" : ""); //重组path
            for(vector<string>::iterator i = v.begin(); i < v.end(); ++i){
                res.append(*i);
                if(i < v.end()-1) res.append("/");
            }
            return res;
        }
    };
  • 相关阅读:
    .Net Attribute详解(下)
    .Net Attribute详解(上)-Attribute本质以及一个简单示例
    美国快递跟踪链接
    ffmpeg中AVBuffer的实现分析
    Android Studio创建JAR/AAR库
    Android Studio添加原生库并自动构建
    代码注释中的专有词——TODO、FIXME和XXX
    adb获得安卓系统版本及截屏
    FFmpeg libavutil主要功能概述
    Linux下库打桩机制分析 function Interposition
  • 原文地址:https://www.cnblogs.com/felixfang/p/3682058.html
Copyright © 2011-2022 走看看