Leetcode Simplify Path

本文介绍了一个简化Unix风格文件绝对路径的算法实现。通过解析输入路径并处理特殊字符,如'.'和'..',来返回规范化的路径。文章还讨论了如何处理连续的斜杠以及特殊情况下的路径处理。

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;
    }
};

 

转载于:https://www.cnblogs.com/xiongqiangcs/p/3847486.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值