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;
    }
};
原文地址:https://www.cnblogs.com/xiongqiangcs/p/3847486.html