Tag:leetcode fb stack
Category:Leetcode
Article From:https://www.cnblogs.com/JTechRoad/p/9060210.html

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;
    }
};

 

Link of this Article: 71. Simplify Path

Leave a Reply

Your email address will not be published. Required fields are marked *