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".
    思考:不断提交修改。。
    class Solution {
    public:
        string simplifyPath(string path) {
            // ..上一级目录
            // .当前目录
            // 根目录下..和.相同
            string ans="";
            vector<string> p; //记录每一级目录
            string temp;
            int len1=path.size();
            int i;
            for(i=0;i<len1;i++)
            {
                if(path[i]=='/')
                {
                    if(temp=="") continue; 
                    else if(temp=="..") 
                    {
                        if(p.empty()) temp=""; //根目录
                        else 
                        {
                            p.pop_back(); //返回上一级目录
                            temp="";
                        }
                    }
                    else if(temp==".") temp="";
                    else 
                    {
                        p.push_back(temp);
                        temp="";
                    }
                }
                else temp+=path[i];
            }
            if(temp!=""&&temp!=".") 
            {
                if(temp=="..")
                {
                    if(!p.empty()) 
                    p.pop_back();
                }
                else p.push_back(temp);
            }
            int len2=p.size();
            if(len2==0) return "/";
            for(i=0;i<len2;i++) ans+='/'+p[i];
            return ans;
        }
    };
    

      

  • 相关阅读:
    docker
    redis 3.2.6 on ubuntu 14.04
    go异常处理
    go语言的命令行库
    iptables
    nsq
    etcd-v2第一集
    rabbitmq, windows/linux, c/c++/node.js/golang/dotnet
    zeromq:c,c++,golang及nodejs使用
    golang下的grpc
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3517522.html
Copyright © 2011-2022 走看看