1. 程式人生 > >71. 簡化路徑 string流

71. 簡化路徑 string流

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/”, => “/a/c”和path = “/a/./b/c/”, => “/a/b/c”, 這樣我們就可以知道中間是”.”的情況直接去掉,是”..”時刪掉它上面挨著的一個路徑,而下面的邊界條件給的一些情況中可以得知,如果是空的話返回”/”,如果有多個”/”只保留一個。那麼我們可以把路徑看做是由一個或多個”/”分割開的眾多子字串,把它們分別提取出來一一處理即可,程式碼如下:

class Solution {
public:
    string simplifyPath(string path) {
        string res, t;
        stringstream ss(path);
        vector<string> v;
        while (getline(ss, t, '/')) {
            if (t == "" || t == ".") continue;
            if (t == ".." && !v.empty()) v.pop_back();
            else if (t != "..") v.push_back(t);
        }
        for (string s : v) res += "/" + s;
        return res.empty() ? "/" : res;
    }
};