[LeetCode] Simplify Path

Given an absolute path for a file (Unix-style), simplify it.

For example,
path = "/home/", => "/home"
path = "/a/./b/../../c/", => "/c"

click to show corner cases.

Corner Cases:

 

    • Did you consider the case where path = "/../"?
      In this case, you should return "/".
    • Another corner case is the path might contain multiple slashes '/' together, such as "/home//foo/".
      In this case, you should ignore redundant slashes and return "/home/foo".

 

 

Hide Tags
 Stack String
 
思路:获取每一段字符串,加入到vector/stack中,若是“."就跳过,若是“..”,从stack中弹出一个元素,否则压入一个字符串。我还用了预处理,处理了有重复‘/’的情况。 另外,所有字符串都以'/'结尾,方便后面的处理,要不然还要在while Loop后面单独处理。 
重点是要想到用stack去处理,我这里面的vector其实和stack是一样的。
class Solution {
    public:
        string delRedundantSlash(string in) 
        {   
            if(in.size() <= 1)
                return in; 
            string out;
            out += in[0];
            for(int i = 1; i < in.size(); i++)
            {   
                if(in[i] == '/' && in[i-1] == '/')
                    continue;
                out += in[i];
            }   

#if 0
            // delete the last '/' if '/' exist at the end
            if( out.size() >= 2
                    && out[out.size() - 1] == '/' 
                    && out[out.size() -2 != '/'] )
            {
                out.erase(out.size()-1, 1);
            }
#endif

            return out;
        }   

        string simplifyPath(string path) 
        {   
            bool isRoot = false;
    
            path = delRedundantSlash(path); 

            if(path.size() <= 1)
                return path;

            // add the '/' at the end of path
            // inorder or handle this more convenient 
            if(path[path.size()-1] != '/')
                path += '/';

            vector<string> st;
            string res;

            size_t pos = path.find('/') ;
            string tmpStr;
            while(pos != string::npos)
            {
                //cout << "path\t" << path << endl;
                //cout << "pos\t" << pos << endl;
                if(pos != 0)
                {
                    tmpStr = path.substr(0, pos);
                    if(tmpStr.size() == 1 && tmpStr == ".")
                        ;// do nothing
                    else if(tmpStr.size() == 2 && tmpStr == "..")
                    {
                        if(!st.empty())
                            st.pop_back();
                    }
                    else
                        st.push_back(tmpStr);
                }
                path = path.substr(pos+1);
                pos = path.find('/') ;
            }


            for(int i = 0; i < st.size(); i++)
                res += '/' + st[i];

            if(res.empty())
                res = "/";

            return res;
        }
};

 

posted @ 2015-03-10 16:26  穆穆兔兔  阅读(214)  评论(0编辑  收藏  举报