Friday, August 21, 2015

071 - Simplify Path

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.

Hide Tags

Stack String

反斜杠作为分隔符,查找并存路径中的名称,遇到 . 略过,遇到 .. 弹出,然后依次恢复即可。

class Solution {
public:
    string simplifyPath(string path) {
        string rst="/";
        int len=path.length();
        if(len)
        {
            int pos=path.find('/'), pre=0;
            string sub="";
            vector<string> stk;

            while(string::npos!=pre)
            {
                if(pos!=pre)
                {
                    sub = path.substr(pre+1, pos-pre-1);

                    if("." == sub)
                        ;                       //do nothing.
                    else if(".." == sub)
                    {
                        if(stk.size())
                            stk.pop_back();
                    }
                    else
                    {
                        if(sub.length())
                            stk.push_back(sub);
                    }
                }
                pre=pos;
                pos=path.find('/', pre+1);
            }
           
            //build result
            int sz=stk.size();
            for(int ii=0; ii<sz; ++ii)
                rst += stk[ii] + ((ii==sz-1) ? "" : "/");
        }
        return rst;
    }
};
8 ms.

No comments:

Post a Comment