71. Simplify Path

https://leetcode.com/problems/simplify-path/description/

class Solution {
public:
    string simplifyPath(string path) {
        int idx = 0;
        vector<string> s;
        while (true) {
            string token = getToken(path, idx);
            if (token == "")    break;
            if (token == ".")   continue;
            if (token == "..") {
                if (s.size() > 0)
                    s.pop_back();
            }
            else
                s.push_back(token);
        }
        
        string res;
        for (auto& t : s) {
            res += "/" + t;
        }
        return res == "" ? "/" : res;
    }
    string getToken(const string& path, int& idx) {
        while (idx < path.length() && path[idx] == '/') idx++;
        if (idx == path.length())   return "";
        int end = idx;
        while (end < path.length() && path[end] != '/') end++;
        string res = path.substr(idx, end-idx);
        idx = end;
        return res;
    }
};

猜你喜欢

转载自www.cnblogs.com/JTechRoad/p/9060210.html