Leetcode 71 Simplify Path

HowieLee59發表於2018-12-23

Given an absolute path for a file (Unix-style), simplify it. 

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"
path = "/a/../../b/../c//.//", => "/c"
path = "/a//b////c/d//././/..", => "/a/b/c"

In a UNIX-style file system, a period ('.') refers to the current directory, so it can be ignored in a simplified path. Additionally, a double period ("..") moves up a directory, so it cancels out whatever the last directory was. For more information, look here: https://en.wikipedia.org/wiki/Path_(computing)#Unix_style

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

這個題的意思是仿照Unix的路徑規劃來進行模擬

class Solution {
public:
    string simplifyPath(string path) {
        path += '/';//首先加上'/'以簡化操作
        string res,s;
        for(auto c : path){
            if(res.empty()){//res為實際的串
                res += c;
            }else if(c != '/'){//讀入正常的串(兩個'/'之間的串)
                s += c;
            }else{
                if(s == ".."){
                    if(res.size() > 1){
                        res.pop_back();
                    }
                    while(res.back() != '/'){//連續退,主要是在兩個'/'為一段很長的串的時候
                        res.pop_back();
                    }
                }else if(s != "" && s != "."){//正常新增
                    res += s + '/';
                }
                s = "";//將這個串清零
            }
        }
        if(res.size() > 1){
            res.pop_back();//去掉'/'
        }
        return res;
    }
};

 

相關文章