• [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".

    思路

    本题就是对输入的字符串逐个处理的过程,但是要注意两个特殊情况,(1)如果在根目录下输入..,则仍在根目录,而不是跳到上级目录。(2)如果有两个分隔符在一块的话就当做一个分隔符处理。我们只要将输入字符串用”/”分割开来得到一个字符串数组,然后对这个数组内的元素依次处理即可。作者新建了一个Path类,该类包含了一个变量按顺序保存了所有到当前路径的目录名称,提供了一个方法对新输入的字符串进行处理,如果当前路径是根路径,遇到..就不做处理(情况1)。如果新来的字符串是”.”或者空(情况2)也不做处理。其他情况下遇到..删除最顶层目录。遇到普通目录新加一个目录。最后输出结果即可。

    代码

    import java.util.ArrayList;
    
    class Path
    
    {
    
       private ArrayList<String> paths=new ArrayList<>();
    
       public void ParseNewDir(String dir)
    
       {
    
       if(dir.equals("")||dir.equals(".")||(dir.equals("..")&&paths.size()==0))
    
          {
    
            return;
    
          }
    
          if(dir.equals(".."))
    
          {
    
            paths.remove(paths.size()-1);
    
          }
    
          else
    
          {
    
            paths.add(dir);
    
          }
    
       }
    
       public String GetFullDir()
    
       {
    
          if(paths.size()==0)
    
            return "/";
    
          StringBuilder sb=new StringBuilder();
    
          for(int i=0;i<paths.size();i++)
    
          {
    
            sb.append("/");
    
            sb.append(paths.get(i));
    
          }
    
          return sb.toString();
    
       }
    
    }
    
    public class Simplify_Path {
    
         public String simplifyPath(String path) {
    
               // Note: The Solution object is instantiated only once and is reused by each test case.
    
               String[] splits=path.split("/");
    
               Path fullDir=new Path();
    
               for(int i=0;i<splits.length;i++)
    
               {
    
               String newDir=splits[i];
    
               fullDir.ParseNewDir(newDir);
    
               }
    
               return fullDir.GetFullDir();
    
           }
    
         public static void main(String[] args)
    
         {
    
            System.out.println(new Simplify_Path().simplifyPath("/../"));
    
         }
    
    }
  • 相关阅读:
    dede模板留言提交错误时返回空白页处理方法
    Dedecms列表页通过函数调用当前文档tag的方法
    织梦dedecms如何让内容页显示不同的内容,但是每次更新都不变
    织梦DedeCMS网站服务器搬家详细教程
    让DEDECMS文章内容中链接新窗口打开的方法
    织梦dedecms中英文模版当前位置的修改方法
    织梦dedecms设置不同的搜索页模板教程
    简易版php文件上传_超详细详解
    nodejs 使用mongoose 操作mongodb
    记一个正则
  • 原文地址:https://www.cnblogs.com/developerY/p/Simplify_Path.html
Copyright © 2020-2023  润新知