欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode·71. Simplify Path

程序员文章站 2022-03-05 11:37:47
...

题目:

71. Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

Corner Cases:

·Did you consider the case where path = "/../"?
    In this case, you should return "/".
·Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
    In this case, you should ignore redundant slashes and return "/home/foo".

思路:

  1. 解决尾部;
  2. 解决"//"情况;
  3. 分割路径处理;

代码:

class Solution {
public:
    string simplifyPath(string path) {
        if(path.size() <= 1)
            return path;

        if(path[path.size()-1] == '/'){
            for(int i = path.size()-1; i > 1; --i){
                if(path[i] == '/')
                    path = path.substr(0, i);
                else
                    break;
            }
        }

        for(int i = 0; i < path.size()-1; ++i){
            if(path[i] == '/' && path[i+1] == '/'){
                path = path.substr(0, i) + path.substr(i+1, path.size());
            }
        }

        vector<string> vec;
        string str = "";
        for(int i = 0; i < path.size(); ++i){
            if(path[i] != '/'){
                str += path[i];
            }else{
                if(str != ""){
                    vec.push_back(str);
                    str = "";
                }
            }
        }vec.push_back(str);

        for(int i = 0; i < vec.size(); ++i){
            if(vec[i] == "."){
                vector<string>::iterator it = vec.begin()+i;
                vec.erase(it);
                --i;
            }else if(vec[i] == ".."){
                vector<string>::iterator it = vec.begin()+i;
                vec.erase(it);
                if(i == 0){
                    --i;
                    continue;
                }

                it = vec.begin()+i-1;
                vec.erase(it);
                --i;--i;
            }
        }

        str = "/";
        for(int i = 0; i < vec.size(); ++i){
            str += vec[i];
            if(i != vec.size()-1)
                str += "/";
        }

        return str;
    }
};

结果:


LeetCode·71. Simplify Path