LeetCode Day57 simplify path

按照’/'将字符串分割,对每个分割出的字符串处理,如果是“…”,则popback,如果是“.”,则跳过,其他则保存。
最后输出结果
我的版本

class Solution {
public:
    string simplifyPath(string path) {
        vector<string> v;
        int flag=0,n=0;
        string s="";
        for(int i=0;i<path.size();i++){
            if(path[i]=='/'){
                if(flag==0) continue;
                else {
                    flag=0;
                    if(s==".."){
                        if(!v.empty()) v.pop_back();}
                    else if(s!=".") v.push_back(s);
                    s="";
                    continue;
                }
            }
            else{
                s+=path[i];
                flag=1;
            }
        }
        if(s==".."&&!v.empty()) v.pop_back();
        else if(s!=""&&s!="."&&s!="..") v.push_back(s);
        if(v.empty()) return "/";
        string res;
        for(int i=0;i<v.size();i++){
            res+=('/'+v[i]);
        }
        return res;
    }
};
class Solution {
public:
    string simplifyPath(string path) {
        vector<string> v;
        int i = 0;
        while (i < path.size()) {
            while (path[i] == '/' && i < path.size()) ++i;
            if (i == path.size()) break;
            int start = i;
            while (path[i] != '/' && i < path.size()) ++i;
            int end = i - 1;
            string s = path.substr(start, end - start + 1);
            if (s == "..") {
                if (!v.empty()) v.pop_back(); 
            } else if (s != ".") {
                v.push_back(s);
            }
        }
        if (v.empty()) return "/";
        string res;
        for (int i = 0; i < v.size(); ++i) {
            res += '/' + v[i];
        }
        return res;
    }
};

简写版

class Solution {
public:
    string simplifyPath(string path) {
        string res, t;
        stringstream ss(path);
        vector<string> v;
        while (getline(ss, t, '/')) {
            if (t == "" || t == ".") continue;
            if (t == ".."){
                if(!v.empty()) v.pop_back();}
            else v.push_back(t);
        }
        for (string s : v) res += "/" + s;
        return res.empty() ? "/" : res;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41394379/article/details/85206338