Simplify Path

题目:

 

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

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

分析:此题主要需注意以下两点

1、结果起码有一个"/"

2、当有一个这样的形式/../,就代表少一个路径

代码如下:

        string simplifyPath(string path) {

        int n=path.length();
        if(n<=1)return path;
        string result;
        int numdot=0,numdoubledot=0,g=0;//分别表示 "."的个数,".."的个数,g其实是个标量
        bool flag=false;
        for(int i=n-1;i>=0;i--)
        {
            if(path[i]=='/')
            {
                if(flag)
                {
                    result=path[i]+result;
                    flag=false;
                }
                if(g)
                {
                    g=0;
                    numdoubledot--;
                }
                numdot=0;
            }
            else if(path[i]=='.')
            {
                if(flag)
                {
                    result=path[i]+result;
                }
                else
                {
                    numdot++;
                    if(numdot==2)
                    {
                        numdot=0;
                        numdoubledot++;
                    }
                }
            }
            else
            {
                if(numdoubledot)
                {
                    g++;
                }
                else
                {
                    result=path[i]+result;
                    flag=true;
                }
            }
        }
        if(result.length()==0)result+=path[0];
        return result;
    }

你可能感兴趣的:(Path)