题目:

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. TCP 建立连接为什么要握 3 次手?

    上次已经说过,没有协议,不成方圆,计算机之间的通信更是依赖于协议.今天就重点分析一下 TCP 协议. 传输控制协议 TCP 是一种面向连接的.可靠的.基于字节流的传输层通信协议,由IETF的RFC 7 ...

  2. 在centOS使用systemctl配置启动多个tomcat

    公司服务器使用的是阿里云CentOS7,CentOS7和CentOS6目前最大区别就是service变成了现在的systemctl,简单的查了一下并结合使用,发现systemctl功能上等同于6上面的 ...

  3. tomcat如何利用waf进行防护

    近期某一实验室遇到一个问题:web环境是windows+tomcat+mysql,检测到cookie注入,此时又不想修改代码.此时两种方案进行解决: 1.利用安软(waf)类进行检测防御.这里国内主要 ...

  4. 支撑大规模公有云的Kubernetes改进与优化 (2)

    接下来我们按照kubernetes创建容器的详细过程,以及可能存在的问题. 一.API Server的认证,鉴权,Quota 当客户需要创建一个pod的时候,需要先请求API Server. Kube ...

  5. 在python中独立运行orm

  6. ngx_lua应用最佳实践

    引子: 以下文字,是UPYUN系统开发工程师timebug在SegmentFault D-Day南京站技术沙龙上所做分享的内容要义提炼,主题为UPYUN系统开发团队在进行业务逻辑由C模块到ngx_lu ...

  7. Vuex了解

    State Vuex是用来管理某个应用的整个状态,那么一个应用只能有一个Vuex实例.和React一样,Vuex也不允许直接去修改state,而是通过提交mutation,来触发状态变更.Vuex的状 ...

  8. BZOJ 1029: [JSOI2007]建筑抢修 优先队列

    1029: [JSOI2007]建筑抢修 Time Limit: 4 Sec  Memory Limit: 162 MB 题目连接 http://www.lydsy.com/JudgeOnline/p ...

  9. 可变参数模拟printf()函数实现一个my_print()函数以及调用可变参数需注意的陷阱

    入栈规则 可变参数函数的实现与函数调用的栈帧结构是密切相关的.所以在我们实现可变参数之前,先得搞清楚 栈是怎样传参的. 正常情况下,C的函数参数入栈遵照__stdcall规则, 它是从右到左的,即函数 ...

  10. List常用子类的特点

    ArrayList:    底层数据结构是数组,查询快,增删慢   线程不安全, 效率较高 Vector   底层数据结构是数组,查询快,增删慢   线程安全, 效率较低 LinkedList   底 ...