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"

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

    题目不难,主要考虑一些特殊情况。

    对于path = "/a/./b/../../c/", => "/c",模拟一下

    先按照'/'对字符串进行分割,得到 [a, . , b, .. , .. , c]

    首先进入目录a,注意 '.' 代表当前目录 ,".."代表上一个目录

    然后到达'.',还是在当前目录,/a

    然后到达'b',这为/a/b

    然后到达'..',这是回到父目录,则变为/a

    然后到达'..',继续回到父目录,则变为/

    然后到达'c',则达到子目录,变为/c

    class Solution {
    public:
        vector<string> split(string& path, char ch){
            int index = 0;
            vector<string> res;
            while(index < path.length()){
                while(index < path.length() && path[index] == '/') index++;
                if(index >= path.length()) break;
                int start=index, len = 0;
                while(index < path.length() && path[index]!='/') {index++;len++;}
                res.push_back(path.substr(start,len));
            }
            return res;
        }
        
        string simplifyPath(string path) {
            vector<string> a = split(path,'/');
            vector<string> file;
            for(int i = 0 ; i < a.size(); ++ i){
                if(a[i] == ".." ){
                    if(!file.empty()) file.pop_back();
                }
                else if(a[i]!=".") file.push_back(a[i]);
            }
            string res="";
            if(file.empty()) res ="/";
            else{
                for(int i = 0 ; i < file.size(); ++ i) res+="/"+file[i];
            }
            return res;
        }
    };
  • 相关阅读:
    hdu1698(线段树区间更新)
    js数组的操作
    grunt构建一个项目
    JS获取当前时间
    页面打开后,几秒后自动跳转
    设置网页图片热点链接
    mongodb的安装
    Linux,activemq-cpp之消息过滤器
    Linux 命令行输入
    第五篇——Spring音乐播放界面设计(C#)
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3847486.html
Copyright © 2011-2022 走看看