leetcode第一刷_Simplify Path

这道题的思路还是比較清晰的,用栈嘛,麻烦是麻烦在这些层次的细节上。主要有以下几个:

./和/:当前路径,遇到这样的,应该将后面的文件夹或文件入栈。

../:上一层路径。遇到这样的。应该做一次出栈操作,相当于返回了上一层文件夹。

//:能够直接简化成‘/’。

还有以下几个要注意的測试用例:

1. linux的路径名能够含有非常多特殊字符,比方“_”,".","*"等等,所以要特别注意含有"."的哪些路径名。

2. 在路径最后的..和.是不须要后面接上'/'的。

代码写的不是非常好。回头应该更正一下:

class Solution {
public:
    string simplifyPath(string path) {
        stack<string> s;
        int len = path.length();
        int i=0;
        string tp, res="";
        while(i<len){
            if(path[i] == '/'){i++;}
            else if(isalnum(path[i])||path[i]=='_'){
                int j=i+1;
                while(path[i-1]=='.') i--;
                while((isalnum(path[j])||path[j]=='_')&&j<len) j++;
                tp = path.substr(i, j-i);
                s.push(tp);
                i = j;
            }else if(path[i] == '.'){
                if(i+1==len)    break;
                else if(path[i+1]=='/') i = i+2;
                else if(path[i+1]=='.'){
                    if(path[i+2] == '/'||i+2==len){
                        i = i+3;
                        if(!s.empty())	s.pop();
                    }else if(path[i+2] == '.'){
                        if(i+3==len||path[i+3] == '/')
                            s.push("...");
                        i = i+3;
                    }else
                        i = i+2;
                }else
                    i = i+1;
            }
        }
        if(s.empty())   res = "/";
        else{
            while(!s.empty()){
                res = "/"+s.top()+res;
                s.pop();
            }
        }
        return res;
    }
};


猜你喜欢

转载自www.cnblogs.com/ldxsuanfa/p/10702087.html