[leetcode]Simplify Path

class Solution {

public:

    string simplifyPath(string path) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        if(path.empty()) return "";

        

        if(path[path.size()-1] != '/') path += "/";

        int N = path.size();

        stack<string> s;

        string tmp;

        

        for(int i = 0; i < N; i++){

            if(path[i] == '/'){

                if(tmp == ".."){

                    if(!s.empty()) s.pop();

                }else if(!tmp.empty() && tmp != "." && tmp != ".."){

                    s.push(tmp);

                }

                tmp.clear();

        

            }else{

                tmp += path[i];

                

            }

        }

        

        //reverse stack

        stack<string> s1;

        while(!s.empty()){

            s1.push(s.top());

            s.pop();

        }

        

        string result = "";

        while(!s1.empty()){

            result += "/";

            result += s1.top();

            s1.pop();

        }

        

        return result == "" ? "/" : result;

        

    }

};


你可能感兴趣的:(LeetCode)