C++ 8ms O(n) complexity O(1) space


  • 0
    Z
    class Solution {
    public:
    string simplifyPath(string path) {
        string s;
        int sz(path.length()), begin(0), len(0);
        for(int i = 1; i <= sz; i++){
            if(!begin && path[i] != '/') begin = i;    //ignore "//"
            else if(begin && (path[i] == '/' || i == sz)) len = i - begin;
            if(len){
                string ns = path.substr(begin, len);
                begin = len = 0;
                if(!ns.compare(".")) continue;    //ignore "."
                else if(!ns.compare("..")){       //go up
                    int j(s.length() - 1);
                    while(s[j] != '/') j--;
                    s = s.substr(0, j);
                }else s += '/' + ns;
            }
        }
        return s.length() ? s : "/";    //must be at least "/"
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.