题目:

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

For example,
path = "/home/", => "/home"

path = "/a/./b/../../c/", => "/c"

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

题解:

这是一道简化路径的题,路径简化的依据是:

当遇到“/../"则需要返回上级目录,需检查上级目录是否为空。

当遇到"/./"则表示是本级目录,无需做任何特殊操作。

当遇到"//"则表示是本级目录,无需做任何操作。

当遇到其他字符则表示是文件夹名,无需简化。

当字符串是空或者遇到”/../”,则需要返回一个"/"。

当遇见"/a//b",则需要简化为"/a/b"。

根据这些要求,我需要两个栈来解决问题。

先将字符串依"/"分割出来,然后检查每个分割出来的字符串。

当字符串为空或者为".",不做任何操作。

当字符串不为"..",则将字符串入栈。

当字符串为"..", 则弹栈(返回上级目录)。

当对所有分割成的字符串都处理完后,检查第一个栈是否为空,如果栈为空,则证明没有可以重建的目录名,返回"/"即可。

当第一个栈不为空时,这时候我们需要还原path。但是不能弹出栈,因为按照要求栈底元素应该为最先还原的目录path。

例如:原始path是 /a/b/c/,栈里的顺序是:a b c,如果依次弹栈还原的话是:/c/b/a(错误!),正确答案为:/a/b/c

所以这里我应用了第二个栈,先将第一个栈元素弹出入栈到第二个栈,然后再利用第二个栈还原回初始path。

代码为:

 1     public String simplifyPath(String path) {
 2         if(path == null||path.length()==0)
 3             return path;
 4         
 5         Stack<String> stack = new Stack<String>();
 6         String[] list = path.split("/");
 7         
 8         for(int i=0; i<list.length; i++){
 9             if(list[i].equals(".")||list[i].length()==0)
                 continue;
             else if(!list[i].equals(".."))
                 stack.push(list[i]);
             else{
                 if(!stack.isEmpty())
                     stack.pop();
             }
         }
         
         StringBuilder res = new StringBuilder();
         
         Stack<String> temp = new Stack<String>();
         while(!stack.isEmpty())  
             temp.push(stack.pop());
         
         while(!temp.isEmpty())
             res.append("/"+temp.pop());
         
         if(res.length()==0)
             res.append("/");
         
         return res.toString();
     }

 这里注意:

判断字符串相等与否要用.equals(),因为是引用类型。

要注意split函数是可以split出空字符的,例如://b/ 会被split结果为["","b"]。

最后使用StringBuilder进行拼接,由于String在每次对字符串修改时候均会生成一个新的String,效率较低,一般会采用StringBuilder或者StringBuffer来进行字符串修改的操作,StringBuilder是StringBuffer的简易替换,是非线程安全的,而StringBuffer是线程安全的。

在网上还看到有人写的最后还原path没用到第二个栈,是因为可以利用Java中LinkedList 数据类型来表示第一个栈。LinkedList数据类型很强大,包含了栈和队列的实现。所以最后还原时调用removeLast()函数就可以解决顺序问题。

引用代码:http://blog.csdn.net/linhuanmars/article/details/23972563

 1     public static String simplifyPath(String path) {  
 2         if(path.length() == 0){  
 3             return path;  
 4         }  
 5           
 6         String[] splits = path.split("/");  
 7         LinkedList<String> stack = new LinkedList<String>();  
 8         for (String s : splits) {  
 9             if(s.length()==0 || s.equals(".")){  
                 continue;  
             }else if(s.equals("..")){  
                 if(!stack.isEmpty()){  
                     stack.pop();  
                 }  
             }else{  
                 stack.push(s);  
             }  
         }  
           
         if(stack.isEmpty()){  
             stack.push("");  
         }  
         String ret = "";  
         while(!stack.isEmpty()){  
             ret += "/" + stack.removeLast();  
         }  
           
         return ret;  
     } 

Simplify Path leetcode java的更多相关文章

  1. Simplify Path [LeetCode]

    Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/", ...

  2. Simplify Path——LeetCode

    Given an absolute path for a file (Unix-style), simplify it. For example,path = "/home/", ...

  3. leetcode面试准备:Simplify Path

    leetcode面试准备:Simplify Path 1 题目 Given an absolute path for a file (Unix-style), simplify it. For exa ...

  4. 【LeetCode】71. Simplify Path 解题报告(Python)

    [LeetCode]71. Simplify Path 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://f ...

  5. 【LeetCode】71. Simplify Path

    Simplify Path Given an absolute path for a file (Unix-style), simplify it. For example,path = " ...

  6. [LintCode] Simplify Path 简化路径

    Given an absolute path for a file (Unix-style), simplify it. Have you met this question in a real in ...

  7. 56. Edit Distance && Simplify Path

    Edit Distance Given two words word1 and word2, find the minimum number of steps required to convert ...

  8. 2.2.5 NIO.2 Path 和 Java 已有的 File 类

    NIO与IO交互 toPath() File -- Path toFile() Path -- File Demo: import java.io.File; import java.nio.file ...

  9. 71. Simplify Path(M)

    71. Simplify Path Given an absolute path for a file (Unix-style), simplify it. For example, path = & ...

随机推荐

  1. python: 模型的统计信息

    /*! * * Twitter Bootstrap * */ /*! * Bootstrap v3.3.7 (http://getbootstrap.com) * Copyright 2011-201 ...

  2. 创建 python 虚拟环境

    conda 创建环境 conda 可以理解为一个工具,也是一个可执行命令,其核心功能是包管理与环境管理.包管理与 pip 的使用类似,环境管理则允许用户方便地安装不同版本的 python 并可以快速切 ...

  3. IDEA导入eclipse项目并部署运行完整步骤(转发)

    首先说明一下:idea里的project相当于eclipse里的workspace,而idea里的modules相当于eclipse里的project 1.File-->Import Proje ...

  4. 【SQL】183. Customers Who Never Order

    Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL qu ...

  5. 理解Django的makemigrations和migrate

    在你改动了 model.py的内容之后执行下面的命令: python manger.py makemigrations 相当于在该app下建立 migrations目录,并记录下你所有的关于modes ...

  6. luoguP5108 仰望半月的夜空 [官方?]题解 后缀数组 / 后缀树 / 后缀自动机 + 线段树 / st表 + 二分

    仰望半月的夜空 题解 可以的话,支持一下原作吧... 这道题数据很弱..... 因此各种乱搞估计都是能过的.... 算法一 暴力长度然后判断判断,复杂度\(O(n^3)\) 期望得分15分 算法二 通 ...

  7. luogu4595 [COCI2011-2012#5] POPLOCAVANJE 后缀自动机

    看着就像后缀自动机.... 然后搜了一下,网上一大把的\(AC\)自动机 嗯...... 不管了,打一个试试 然后就过了\(QAQ\) 我们考虑对于每个点\(i\)求出它往前最长能匹配的子串的长度 可 ...

  8. Linux怎么开启ssh

    一.查看ssh开启状态 service ssh status 这是已经开启了的状态 二.如果没有开启  键入以下命令开启 service ssh start 三.开启后如果不能利用xshell远程访问 ...

  9. poj 3264 线段树

    题目意思:给定Q(1<=Q<=200000)个数A1,A2,```,AQ, 多次求任一区间Ai-Aj中最大数和最小数的差 线段树太弱了,题目逼格一高连代码都读不懂,今天开始重刷线段树,每天 ...

  10. Java并发(十七):ConcurrentHashMap

    先做总结: 1.HashMap HashTable ConcurrentHashMap HashMap:线程不安全 HashTable:线程安全,每个方法都加了 synchronized 修饰.类似 ...