71.Simplify Path

来源:互联网 发布:by2为什么不红了知乎 编辑:程序博客网 时间:2024/05/16 09:33

思路:用栈,遇到/./或者结尾是/.或者//什么都不做,继续遍历;遇到/../或者结尾是/..就将栈顶元素一直出栈直到遇到“/”为止;遇到其他元素就入栈。本题思路简单,但是写起来很容易出错。特别是在出栈前要判断栈是否为空,以及类似于/.../这样的情况怎么处理。

class Solution {

public:
    string simplifyPath(string path) {
        //process
        stack<char> result;
        int len=path.size();
        for(int i=0;i<len;++i){
                if(path[i]=='/'){
                        if(i+2<len && path[i+1]=='.' && path[i+2]=='.' && (i+3>=len || path[i+3]=='/') ){
                                if(!result.empty()){
                                        while(!result.empty() && result.top()!='/'){
                                        result.pop();
                                        }
                                        result.pop();
                                }
                                i+=2;
                        }else if(i+1<len && path[i+1]=='.' && (i+2>=len || path[i+2]=='/')){
                                i+=1;
                        }else if(i+1<len && path[i+1]!='/'){
                                result.push(path[i]);//add '/'
                        }
                }else{
                        result.push(path[i]);
                }
        }
        //end
        if(result.empty()){
                return "/";
        }
        stack<char> reverse_result;
        while(!result.empty()){
                reverse_result.push(result.top());
                result.pop();
        }
        string s;
        while(!reverse_result.empty()){
                s+=reverse_result.top();
                reverse_result.pop();
        }
        return s;
    }
};
0 0
原创粉丝点击