题目:

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. php开启memcache扩展

    1.下载memcache.dll(php7)https://github.com/nono303/PHP7-memcahe-dll/tree/master 2.将dll文件放到php7/ext目录下 ...

  2. 使用IIS实现反向代理

    IIS的反向代理是通过ARR模块来完成的,ARR模块需要另外安装,而且只能通过Web PlatForm Installer安装.关于安装来源与步骤,帖子已有很多,不做描述.启用“Application ...

  3. BZOJ 2151 种树(循环链表)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=2151 [题目大意] 在一个长度为n的数字环中挑选m个不相邻的数字使得其和最大 [题解] ...

  4. 【贪心】【后缀自动机】Gym - 101466E - Text Editor

    题意:给你两个串A,B,以及一个整数K,让你找到B的一个尽可能长的前缀,使得其在A串中出现的次数不小于K次. 对A串建立后缀自动机,然后把B串放在上面跑,由于每到一个结点,该结点endpos集合的大小 ...

  5. 【搜索+DP】codevs1066-引水入城

    [题目大意] 一个N行M列的矩形,如上图所示,其中每个格子都代表一座城 市,每座城市都有一个海拔高度.现在要在某些城市建造水利设施.水利设施有两种,分别为蓄水厂和输水站.蓄水厂的功能是利用水泵将湖泊中 ...

  6. Caffe2(3)----下载现成的模型并使用

    Caffe2训练好的模型可在Model Zoo下载,下载的命令很简单,接下来以下载和使用squeezenet为例,进行简单说明. 1.浏览可下载的模型 已有模型都放在github上,地址:https: ...

  7. MyBatis insert 返回主键的方法

    数据库:SqlServer2005 表结构: /*==============================================================*//* Table: D ...

  8. 关闭IE8的首次运行自定义设置

    方法一:顺着IE8的提示,一步一步的了解看完或设置完等的,它“推荐”的你应该做的事,然后重新设置首页就行了. 方法二:开始->运行->输入:gpedit.msc->用户配置-> ...

  9. .Net高级技术——IDisposable

    IDisposable概述 GC(垃圾收集器)只能回收托管(Managed)内存资源,对于数据库连接.文件句柄.Socket连接等这些资源(非托管资源,UnManaged)就无能为例,必须程序员自己控 ...

  10. C#编程(十)----------C#预处理器

    原文链接:http://blog.csdn.net/shanyongxu/article/details/46491757 C#中的预处理器指令 #IF 如果 C# 编译器遇到最后面跟有 #endif ...