Share my clear cpp solution


  • 0
    R
    class Solution {
    public:
        string simplifyPath(string path) {
            if (path.size() == 0) return "";
            if (path[path.size()-1]!='/') path.push_back('/');
            string res, tmp;
            int i = 0;
            while (i < path.size()) {
                tmp.clear();
                // get next level path, like as /xxx
                if (path[i] == '/') {
                    tmp.push_back(path[i++]);
                    while (i<path.size()&&path[i] != '/') {
                        tmp.push_back(path[i++]);
                    }
                }
                if (!strcmp(tmp.c_str(), "/.")||
                    !strcmp(tmp.c_str(), "/")) 
                    continue;
                else if (!strcmp(tmp.c_str(), "/..")) { // return to the up level
                    while (res.size()>0&&res[res.size()-1]!='/')
                        res.pop_back();
                    if (res.size()>0) // need pop '/'
                        res.pop_back(); 
                } else
                    res.append(tmp); 
            }
            if (res.empty()) return "/";
            return res;
        }
    };

Log in to reply
 

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