zoukankan      html  css  js  c++  java
  • 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;
        }

  • 相关阅读:
    defer与async的区别
    Promise 的含义
    SCSS 与 Sass 异同
    CSS总结2
    CSS总结1
    jQuery-插件,优化
    jQuery-表格以及表单
    jQuery-事件以及动画
    jQuery-ajax
    jQuery-DOM操作
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3093733.html
Copyright © 2011-2022 走看看