题目:

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. JAVAEE——ssm综合练习:CRM系统(包含ssm整合)

    1 CRM项目外观   1. 开发环境 IDE: Eclipse Mars2 Jdk: 1.7 数据库: MySQL 2. 创建数据库 数据库sql文件位置如下图: 创建crm数据库,执行sql 效果 ...

  2. ROT13 加密与解密

    ROT13简介: ROT13(回转13位)是一种简易的替换式密码算法.它是一种在英文网络论坛用作隐藏八卦.妙句.谜题解答以及某些脏话的工具,目的是逃过版主或管理员的匆匆一瞥.ROT13 也是过去在古罗 ...

  3. ServletConfig对象和ServletContext对象

    (1)ServletConfig:用来保存一个Servlet的配置信息的(比如 : name, class, url ... ) 这些配置信息没什么大用处,我们还可以在ServletConfig中保存 ...

  4. Hdu4903 The only survival

    The only survival Time Limit: 40000/20000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Ot ...

  5. 【Python3】【贪心】hdu4296 Buildings

    题意: n个板,每个板有重量和强度w和s,还有PDV值(上面的总重量-该板的强度) 对于某种叠放方式,PDV的最大值为其代表值 求该值的最小值   考虑只有两个板的情况:a和b,很显然下面的比上面的容 ...

  6. ngx_lua配置及应用

    一.说明 这里不对lua语言本身及其编译器运行环境等做介绍,以下所有介绍前提对lua相关有所了解. 二.ngx_lua介绍 原理 ngx_lua将Lua嵌入Nginx,可以让Nginx执行Lua脚本, ...

  7. 【洛谷】NOIP提高组模拟赛Day2【动态开节点/树状数组】【双头链表模拟】

    U41571 Agent2 题目背景 炎炎夏日还没有过去,Agent们没有一个想出去外面搞事情的.每当ENLIGHTENED总部组织活动时,人人都说有空,结果到了活动日,却一个接着一个咕咕咕了.只有不 ...

  8. IE7 css兼容问题

    1,float:right; 在IE错位问题 : 使用position:absolute:right:0px; 2,汉字在float状态下 折行 ,可能是因为父级宽度不够, 改用 display:in ...

  9. Loj10167 HDU2089 不要62

    题目描述 杭州人称那些傻乎乎粘嗒嗒的人为 626262(音:laoer). 杭州交通管理局经常会扩充一些的士车牌照,新近出来一个好消息,以后上牌照,不再含有不吉利的数字了,这样一来,就可以消除个别的士 ...

  10. Spring Batch 批处理框架介绍

    前言 在大型的企业应用中,或多或少都会存在大量的任务需要处理,如邮件批量通知所有将要过期的会员,日终更新订单信息等.而在批量处理任务的过程中,又需要注意很多细节,如任务异常.性能瓶颈等等.那么,使用一 ...