LeetCode 71. 簡化路徑

來源:互聯網
上載者:User

標籤:top   stream   col   continue   size   amp   多個   empty   class   

給定一個文檔 (Unix-style) 的完全路徑,請進行路徑簡化。

例如,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

邊界情況:

    • 你是否考慮了 路徑 = "/../" 的情況?
    • 在這種情況下,你需返回 "/" 。
    • 此外,路徑中也可能包含多個斜杠 ‘/‘ ,如 "/home//foo/" 。
      在這種情況下,你可忽略多餘的斜杠,返回 "/home/foo" 。

首先應該明確,"."和".."都是目錄。因此,適合將/作為分隔字元,將目錄全部分開。為了方便,總是使得路徑最後一個字元為‘/‘。如果是這樣做的話,需要注意棧為空白的情況。

class Solution {public:    string simplifyPath(string path) {        stack<string> s;        if(path.size() > 1 && path.back() != ‘/‘) {            path.push_back(‘/‘);        }        for(int i = 0; i < path.size(); ) {            while(i < path.size() && path[i] == ‘/‘) {                i++;            }            int j = i + 1;            while(j < path.size() && path[j] != ‘/‘) {                j++;            }            //[i, j),j是第一個/            string cur = path.substr(i, j - i);            if(cur == "..") {                if(!s.empty()) {                    s.pop();                }            } else if(cur == "") {                break;            } else if(cur != ".") {                s.push(cur);            }            i = j;        }        string res;        while(!s.empty()) {            res.insert(0, "/" + s.top());            s.pop();        }        return res == ""? "/": res;    }};

另一種使用getline的方法更清晰:

class Solution {public:    string simplifyPath(string path) {        string res, tmp;        vector<string> stk;        stringstream ss(path);        while(getline(ss,tmp,‘/‘)) {        //  用/作為分隔字元(預設是分行符號,第三個參數為自訂的分隔字元)            if (tmp == "" || tmp == ".") continue;            if (tmp == ".." && !stk.empty())                 stk.pop_back();            else if (tmp != "..")                stk.push_back(tmp);        }        for(auto str : stk) res += "/"+str;        return res.empty() ? "/" : res;    }};

 

LeetCode 71. 簡化路徑

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.