the runtime of my C++ solution beats 99.53% of cpp submissions.


  • 0
    L

    The screenshot.
    0_1488536346920_upload-792e6374-1239-4a71-962e-35cd37dad06d

    My solution using the vector to store the simplified path:
    1.add a '/' for each path;
    2.using the vector to storing the simplified path;
    3.during the iteration, do something special when means “/./”,"/../"."//";
    4.after the iteration, handle the ’/‘ in the tail of the path.

    And the code attached,

    string simplifyPath(string path) {
        path = path + '/';
        vector<char> result(1,'/');
    
        for (string::iterator i = path.begin(); i != path.end(); i++) {
            if (*i == '/') {
                vector<char>::reverse_iterator j = result.rbegin();
                if (*j == '/') continue;
                else if (*j == '.' && *(j + 1) == '/') {
                    result.pop_back();
                } else if (*j == '.' && *(j + 1) == '.'&& *(j + 2) == '/') {
                    if (j + 3 == result.rend()) {
                         result.erase(result.begin() + 1, result.end()); 
                    } else {
                        j = j + 3;
                        while (*j  != '/') {
                          j++;
                         }
                         result.erase(j.base(), result.end());
                     }
                } else {
                    result.push_back(*i);
                }
              } else {
                    result.push_back(*i);
              }
            }
            if(result.size()>1 && result[result.size()-1] == '/')
                result.pop_back();
            return string(result.begin(), result.end());
      }

Log in to reply
 

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