simplify path

class Solution {
public:
    string simplifyPath(string path) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        stack<string> s;
        string str;
        for(int i = 0; i < path.size(); i++)
        {
            if (path[i] == '/')
            {
                if (str == "..")
                    if (!s.empty())
                        s.pop();
                else if (str != "." && str != "")
                    s.push(str);

                str = "";
            }
            else
                str += path[i];
        }
        
        if (str == "..")
            if (!s.empty())
                s.pop();
        else if (str != "." && str != "")
            s.push(str);
        
        if (s.empty())
            return "/";
        
        string ret;
        while(!s.empty())
        {
            ret = "/" + s.top() + ret;
            s.pop();
        }
        
        return ret;
    }
};

 

posted on 2013-09-08 11:07  jumping_grass  阅读(158)  评论(0)    收藏  举报

导航